字符串進行壓縮


壓縮字符串

 1     /// <summary>
 2     /// 壓縮操作類
 3     /// </summary>
 4     public static class Compression
 5     {
 6         /// <summary>
 7         /// 對byte數組進行壓縮
 8         /// </summary>
 9         /// <param name="data">待壓縮的byte數組</param>
10         /// <returns>壓縮后的byte數組</returns>
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         /// <summary>
26         /// 對byte[]數組進行解壓
27         /// </summary>
28         /// <param name="data">待解壓的byte數組</param>
29         /// <returns>解壓后的byte數組</returns>
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         /// <summary>
45         /// 對字符串進行壓縮
46         /// </summary>
47         /// <param name="value">待壓縮的字符串</param>
48         /// <returns>壓縮后的字符串</returns>
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         /// <summary>
61         /// 對字符串進行解壓
62         /// </summary>
63         /// <param name="value">待解壓的字符串</param>
64         /// <returns>解壓后的字符串</returns>
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=="


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM