码迷,mamicode.com
首页 > Windows程序 > 详细

C#字符串压缩与解压

时间:2016-03-11 12:05:17      阅读:510      评论:0      收藏:0      [点我收藏+]

标签:

 1 public static string CompressString(string str)
 2 {
 3     var compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
 4     var compressAfterByte = Compress(compressBeforeByte);
 5     string compressString = Convert.ToBase64String(compressAfterByte);
 6     return compressString;
 7 }
 8 
 9 public static string DecompressString(string str)
10 {
11     var compressBeforeByte = Convert.FromBase64String(str);
12     var compressAfterByte = Decompress(compressBeforeByte);
13     string compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
14     return compressString;
15 }
16 
17 /// <summary>
18 /// Compress
19 /// </summary>
20 /// <param name="data"></param>
21 /// <returns></returns>
22 private static byte[] Compress(byte[] data)
23 {
24     try
25     {
26     var ms = new MemoryStream();
27     var zip = new GZipStream(ms, CompressionMode.Compress, true);
28     zip.Write(data, 0, data.Length);
29     zip.Close();
30     var buffer = new byte[ms.Length];
31     ms.Position = 0;
32     ms.Read(buffer, 0, buffer.Length);
33     ms.Close();
34     return buffer;
35 
36     }
37     catch (Exception e)
38     {
39     throw new Exception(e.Message);
40     }
41 }
42 
43 /// <summary>
44 /// Decompress
45 /// </summary>
46 /// <param name="data"></param>
47 /// <returns></returns>
48 private static byte[] Decompress(byte[] data)
49 {
50     try
51     {
52     var ms = new MemoryStream(data);
53     var zip = new GZipStream(ms, CompressionMode.Decompress, true);
54     var msreader = new MemoryStream();
55     var buffer = new byte[0x1000];
56     while (true)
57     {
58         var reader = zip.Read(buffer, 0, buffer.Length);
59         if (reader <= 0)
60         {
61         break;
62         }
63         msreader.Write(buffer, 0, reader);
64     }
65     zip.Close();
66     ms.Close();
67     msreader.Position = 0;
68     buffer = msreader.ToArray();
69     msreader.Close();
70     return buffer;
71     }
72     catch (Exception e)
73     {
74     throw new Exception(e.Message);
75     }
76 }

 

C#字符串压缩与解压

标签:

原文地址:http://www.cnblogs.com/hzzhao/p/5264620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!