C#使⽤GZip对字符串压缩和解压 1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.IO;
6using System.IO.Compression;
7using System.Data;
8
9namespace Demo
10 {
11public class ZipHelper
12 {
13///<summary>字符串长度压缩
14///解压
15///</summary>
16///<param name="Value"></param>
17///<returns></returns>
18public static DataSet GetDatasetByString(string Value)
19 {
20 DataSet ds = new DataSet();
21string CC = GZipDecompressString(Value);
22 System.IO.StringReader Sr = new StringReader(CC);
23 ds.ReadXml(Sr);
24return ds;
25 }
26///<summary>
27///根据DATASET压缩字符串
28///</summary>
29///<param name="ds"></param>
30///<returns></returns>
31public static string GetStringByDataset(string ds)
32 {
33return GZipCompressString(ds);
34 }
35///<summary>
36///将传⼊字符串以GZip算法压缩后,返回Base64编码字符
37///</summary>
38///<param name="rawString">需要压缩的字符串</param>
39///<returns>压缩后的Base64编码的字符串</returns>
40public static string GZipCompressString(string rawString)
41 {
42if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
43 {
44return"";
45 }
46else
47 {
48byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
49byte[] zippedData = Compress(rawData);
50return (string)(Convert.ToBase64String(zippedData));
51 }
52
53 }
54///<summary>
55/// GZip压缩
56///</summary>
57///<param name="rawData"></param>
58///<returns></returns>
59public static byte[] Compress(byte[] rawData)
60 {
61 MemoryStream ms = new MemoryStream();
62 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
63 compressedzipStream.Write(rawData, 0, rawData.Length);
64 compressedzipStream.Close();
65return ms.ToArray();
66 }
67///<summary>
68///将传⼊的⼆进制字符串资料以GZip算法解压缩
69///</summary>
70///<param name="zippedString">经GZip压缩后的⼆进制字符串</param>
71///<returns>原始未压缩字符串</returns>
72public static string GZipDecompressString(string zippedString)
73 {
74if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
75 {
76return"";
77 }
78else
79 {
80byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
81return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));
82 }
83 }
84///<summary>
85/// ZIP解压
86///</summary>
87///<param name="zippedData"></param>
88///<returns></returns>
89public static byte[] Decompress(byte[] zippedData)
90 {
91 MemoryStream ms = new MemoryStream(zippedData);
92 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
93 MemoryStream outBuffer = new MemoryStream();
94byte[] block = new byte[1024];
95while (true)
96 {
97int bytesRead = compressedzipStream.Read(block, 0, block.Length);
98if (bytesRead <= 0)
99break;
100else
101 outBuffer.Write(block, 0, bytesRead);
102 }
103 compressedzipStream.Close();
104return outBuffer.ToArray();
105 }
106 }
107 }
字符串压缩备⽤!
=================
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论