C#字符串压缩与解压 1public static string CompressString(string str)
2 {
3var compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
4var compressAfterByte = Compress(compressBeforeByte);
5string compressString = Convert.ToBase64String(compressAfterByte);
6return compressString;
7 }
8
9public static string DecompressString(string str)
10 {
11var compressBeforeByte = Convert.FromBase64String(str);
12var compressAfterByte = Decompress(compressBeforeByte);
13string compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
14return compressString;
15 }
16
17///<summary>
18/// Compress
19///</summary>
20///<param name="data"></param>
21///<returns></returns>
字符串长度压缩22private static byte[] Compress(byte[] data)
23 {
24try
25 {
26var ms = new MemoryStream();
27var zip = new GZipStream(ms, CompressionMode.Compress, true);
28 zip.Write(data, 0, data.Length);
29 zip.Close();
30var buffer = new byte[ms.Length];
31 ms.Position = 0;
32 ms.Read(buffer, 0, buffer.Length);
33 ms.Close();
34return buffer;
35
36 }
37catch (Exception e)
38 {
39throw new Exception(e.Message);
40 }
41 }
42
43///<summary>
44/// Decompress
45///</summary>
46///<param name="data"></param>
47///<returns></returns>
48private static byte[] Decompress(byte[] data)
49 {
50try
51 {
52var ms = new MemoryStream(data);
53var zip = new GZipStream(ms, CompressionMode.Decompress, true);
54var msreader = new MemoryStream();
55var buffer = new byte[0x1000];
56while (true)
57 {
58var reader = zip.Read(buffer, 0, buffer.Length);
59if (reader <= 0)
60 {
61break;
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();
70return buffer;
71 }
72catch (Exception e)
73 {
74throw new Exception(e.Message);
75 }
76 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论