字符串进行压缩


压缩字符串

 1     /// 
 2     /// 压缩操作类
 3     /// 
 4     public static class Compression
 5     {
 6         /// 
 7         /// 对byte数组进行压缩
 8         /// 
 9         /// 待压缩的byte数组
10         /// 压缩后的byte数组
11         public static byte[] Compress(byte[] data)
12         {
13             using (MemoryStream ms = new MemoryStream())
14             {
15                 GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
16                 zip.Write(data, 0, data.Length);
17                 zip.Close();
18                 byte[] buffer = new byte[ms.Length];
19                 ms.Position = 0;
20                 ms.Read(buffer, 0, buffer.Length);
21                 return buffer;
22             }
23         }
24 
25         /// 
26         /// 对byte[]数组进行解压
27         /// 
28         /// 待解压的byte数组
29         /// 解压后的byte数组
30         public static byte[] Decompress(byte[] data)
31         {
32             using (MemoryStream tmpMs = new MemoryStream())
33             {
34                 using (MemoryStream ms = new MemoryStream(data))
35                 {
36                     GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
37                     zip.CopyTo(tmpMs);
38                     zip.Close();
39                 }
40                 return tmpMs.ToArray();
41             }
42         }
43 
44         /// 
45         /// 对字符串进行压缩
46         /// 
47         /// 待压缩的字符串
48         /// 压缩后的字符串
49         public static string Compress(string value)
50         {
51             if (string.IsNullOrEmpty(value))
52             {
53                 return string.Empty;
54             }
55             byte[] bytes = Encoding.UTF8.GetBytes(value);
56             bytes = Compress(bytes);
57             return Convert.ToBase64String(bytes);
58         }
59 
60         /// 
61         /// 对字符串进行解压
62         /// 
63         /// 待解压的字符串
64         /// 解压后的字符串
65         public static string Decompress(string value)
66         {
67             if (string.IsNullOrEmpty(value))
68             {
69                 return string.Empty;
70             }
71             byte[] bytes = Convert.FromBase64String(value);
72             bytes = Decompress(bytes);
73             return Encoding.UTF8.GetString(bytes);
74         }
75     }

 Compression.Compress("hello你好666") --->"H4sIAAAAAAAEAMtIzcnJf7J3wdOle83MzAC/qg0wDgAAAA=="