使用C#对文件/流进行GZip\Deflate 的压缩和解压缩
private void GZipProcess(Stream src, Stream desc, CompressionMode mode)
{
int len = 1024000;
byte[] buffer = new byte[len];
using (GZipStream compress = (mode == CompressionMode.Compress) ? new GZipStream(desc, CompressionLevel.Optimal) : new GZipStream(src, CompressionMode.Decompress))
{
if (mode == CompressionMode.Compress)
{
//循环写入压缩的流
while ((len = src.Read(buffer, 0, buffer.Length)) > 0)
{
compress.Write(buffer, 0, len);
}
desc.Flush();
}
else
{
//循环读取解压的流
while ((len = compress.Read(buffer, 0, buffer.Length)) > 0)
{
desc.Write(buffer, 0, len);
}
desc.Flush();
}
}
}
评论