用SharpZipLib里面的BZip2压缩和解压

ICSharpCode.SharpZipLib 类库可以从这里下载。

这几天在搜索关于C#的BZip2压缩和解压代码时候发现很多时候是这个zhuweisky 博客里面的

后来又出了修正版本 利用BZip2.Compress,BZip2.Decompress 实现

但是我发现用BZip2OutputStream和BZip2InputStream 实现,解压时候出现只能解压一部分数据

经过调试其实是代码没有完全用正确.

之前的代码

public static class ZipHelper
{
public static byte[] Zip(byte[] data)
{
MemoryStream mstream = new MemoryStream();
BZip2OutputStream zipOutStream = new BZip2OutputStream(mstream);
zipOutStream.Write(data, 0, data.Length);
zipOutStream.Finalize();
zipOutStream.Close();

byte[] result = mstream.ToArray();
mstream.Close();

return result;
}

public static byte[] Unzip(byte[] data)
{
MemoryStream mstream = new MemoryStream(data);
BZip2InputStream zipInputStream = new BZip2InputStream(mstream);
byte[] byteUncompressed = new byte[zipInputStream.Length];
zipInputStream.Read(byteUncompressed, 0, (int)byteUncompressed.Length);

zipInputStream.Close();
mstream.Close();

return byteUncompressed;
}
}

修改后的

    class ZipHelper
{
public static byte[] Zip(byte[] data)
{
MemoryStream mstream = new MemoryStream();
BZip2OutputStream zipOutStream = new BZip2OutputStream(mstream);
zipOutStream.Write(data, 0, data.Length);
zipOutStream.Close();
byte[] result = mstream.ToArray();
mstream.Close();
return result;
}
public static byte[] Unzip(byte[] data)
{
MemoryStream mstream = new MemoryStream(data);
BZip2InputStream zipInputStream = new BZip2InputStream(mstream);
StreamReader readstream = new StreamReader(zipInputStream,Encoding.Default);
String unzipdata = readstream.ReadToEnd();

zipInputStream.Close();
mstream.Close();
return Encoding.Default.GetBytes(unzipdata);
}


}

解压时候也要注意下跟压缩的时候的编码对应.


你可能感兴趣的:(bzip2)