上面是压缩的部分 不过是简易形式 首先你需要创建或提供一个有效流 然后再new GZipStream(ms, CompressionMode.Compress))眨呀一看也还是挺简单的吗ms 是需要存放被压缩的文件流 然后再把你需要的进行压缩的字节写到GZipStream中最后在一个Dispose
- public static byte[] GZipCompress(byte[] bytes)
- {
- using (MemoryStream ms = new MemoryStream())
- {
- using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress))
- zs.Write(bytes, 0, bytes.Length);
- return ms.ToArray();
- }
- }
上面是解压部4.0可以使用GZipStream.CopyTo函数而不必向我上述有些麻烦的搞定问题 解压需要提供一个包含需要被解压的流数据 然后我们在 new GZipStream(ms, CompressionMode .Decompress)只是两个提供的量不一 下面我们就开始读取解压流中的数据 不过解压流是没办法确定 长度的有些人是在已经压缩好的流中额外添加一部分流用于寄存原始长度 不过那些我想一般是用不到
- public static byte[] GZipDecompress(byte[] bytes)
- {
- using (MemoryStream ms = new MemoryStream(bytes))
- {
- using (GZipStream zs = new GZipStream(ms, CompressionMode.Decompress))
- {
- byte[] buffer = new byte[512];
- MemoryStream buf = new MemoryStream();
- for (int offset; (offset = zs.Read(buffer, 0, 512)) > 0;)
- buf.Write(buffer, 0, offset);
- return buf.ToArray();
- }
- }
- }
上面是通过GZip.dll进行压缩的代码部分 实际上Compress部分一般是要循环压缩字节的不过 只是简单 的给大家一个用法到没必要搞得那么专业 不过GZip.dll我记得是默认集成在Win8中毕竟是微软的玩意
- public byte[] GZipCompress(byte[] bytes)
- {
- int hContext = 0; // 正文句柄
- int input_used = 0; // 未压缩尺寸
- int output_used = 0; // 压缩后尺寸
- InitCompression(); // 初始化压缩
- CreateCompression(ref hContext, GZIP_LVL); // 创建压缩正文
- byte[] buffer = new byte[512]; // 压缩缓冲区
- if (Compress(hContext, bytes, bytes.Length, buffer, 512, ref input_used, ref output_used, GZIP_LVL) != 0)
- Console.WriteLine("error"); // 压缩失败
- DestroyCompression(hContext); // 销毁正文对象
- return buffer;
- }
不过看来看去我还是认为用GZipStream要人性化的多使用API也只是用在C++或E语言的情况下否则 我人也为也没有任何必要搞那么麻烦去写一个利用GZip.dll中导出的函数进行文件的解压缩。
- public byte[] GZipDecompress(byte[] bytes)
- {
- int hContext = 0; // 正文句柄
- int input_used = 0; // 输入尺寸
- int output_used = 0; // 输出尺寸
- InitCompression(); // 初始化解压
- CreateCompression(ref hContext, GZIP_LVL); // 创建解压正文
- byte[] buffer = new byte[512]; // 解压缓冲区
- if (Decompress(hContext, bytes, bytes.Length, buffer, 512, ref input_used, ref output_used) != 0)
- Console.WriteLine("error"); // 解压失败
- DestroyCompression(hContext); // 销毁正文对象
- return buffer;
- }
来源: http://www.phpxs.com/code/1004450/