代码改变世界

使用.Net自带的GZipStream进行流压缩与解压

2014-04-17 14:57  咒语  阅读(1172)  评论(0编辑  收藏  举报
 1 using System.IO;
 2 using System.IO.Compression;
 3 using System.Text;
 4 
 5 namespace CS.Utility
 6 {
 7     /// <summary>
 8     /// 压缩与解压缩处理
 9     /// </summary>
10     public static class Compressor
11     {
12 
13         /// <summary>
14         /// 压缩字符串
15         /// </summary>
16         /// <param name="str"></param>
17         /// <returns></returns>
18         public static byte[] Compress(string str)
19         {
20             var data = Encoding.UTF8.GetBytes(str);
21             return Compress(data);
22         }
23 
24         /// <summary>
25         /// 压缩二进制流
26         /// </summary>
27         /// <param name="data"></param>
28         /// <returns></returns>
29         public static byte[] Compress(byte[] data)
30         {
31             using (var memoryStream = new MemoryStream())
32             {
33                 using (var compressionStream = new GZipStream(memoryStream, CompressionMode.Compress))
34                 {
35                     compressionStream.Write(data, 0, data.Length);
36                     compressionStream.Flush();
37                 }
38                 //必须先关了compressionStream后才能取得正确的压缩流
39                 return memoryStream.ToArray();
40             }
41         }
42 
43         /// <summary>
44         /// 解压二进制流
45         /// </summary>
46         /// <param name="data"></param>
47         /// <returns></returns>
48         public static byte[] Depress(byte[] data)
49         {
50             using (var memoryStream = new MemoryStream(data))
51             using (var outStream = new MemoryStream())
52             {
53                 using (var compressionStream = new GZipStream(memoryStream, CompressionMode.Decompress))
54                 {
55                     compressionStream.CopyTo(outStream);
56                     compressionStream.Flush();
57                 }
58                 return outStream.ToArray();
59             }
60         }
61     }
62 }

参考资料:http://msdn.microsoft.com/zh-cn/library/ms404280(v=vs.110).aspx