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

 1 using System.IO;
 2 using System.IO.Compression;
 3 using System.Text;
 4 
 5 namespace CS.Utility
 6 {
 7     /// 
 8     /// 压缩与解压缩处理
 9     /// 
10     public static class Compressor
11     {
12 
13         /// 
14         /// 压缩字符串
15         /// 
16         /// 
17         /// 
18         public static byte[] Compress(string str)
19         {
20             var data = Encoding.UTF8.GetBytes(str);
21             return Compress(data);
22         }
23 
24         /// 
25         /// 压缩二进制流
26         /// 
27         /// 
28         /// 
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         /// 
44         /// 解压二进制流
45         /// 
46         /// 
47         /// 
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

你可能感兴趣的:(使用.Net自带的GZipStream进行流压缩与解压)