GZip、Deflate压缩算法对应的C#压缩解压函数

GZip解压函数
View Code

GZip压缩函数
View Code
1 /// <summary>
2 /// GZip压缩函数
3 /// </summary>
4 /// <param name="data"></param>
5 /// <returns></returns>
6 public byte[] GZipCompress(byte[] data)
7 {
8 using (MemoryStream stream = new MemoryStream())
9 {
10 using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress))
11 {
12 gZipStream.Write(data, 0, data.Length);
13 gZipStream.Close();
14 }
15 return stream.ToArray();
16 }
17 }

Deflate解压函数
View Code
1 /// <summary>
2 /// Deflate解压函数
3 /// JS:var details = eval('(' + utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法
4 /// </summary>
5 /// <param name="strSource"></param>
6 /// <returns></returns>
7 public string DeflateDecompress(string strSource)
8 {
9 byte[] buffer = Convert.FromBase64String(strSource);
10 using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
11 {
12 ms.Write(buffer, 0, buffer.Length);
13 ms.Position = 0;
14 using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
15 {
16 stream.Flush();
17 int nSize = 16 * 1024 + 256; //假设字符串不会超过16K
18 byte[] decompressBuffer = new byte[nSize];
19 int nSizeIncept = stream.Read(decompressBuffer, 0, nSize);
20 stream.Close();
21 return System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept); //转换为普通的字符串
22 }
23 }
24 }

Deflate压缩函数
View Code
1 /// <summary>
2 /// Deflate压缩函数
3 /// </summary>
4 /// <param name="strSource"></param>
5 /// <returns></returns>
6 public string DeflateCompress(string strSource)
7 {
8 if (strSource == null || strSource.Length > 8 * 1024)
9 throw new System.ArgumentException("字符串为空或长度太大!");
10 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource);
11 using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
12 {
13 using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true))
14 {
15 stream.Write(buffer, 0, buffer.Length);
16 stream.Close();
17 }
18 byte[] compressedData = ms.ToArray();
19 ms.Close();
20 return Convert.ToBase64String(compressedData); //将压缩后的byte[]转换为Base64String
21 }
22 }

posted @ 2011-04-28 16:16  吾爱易逝  阅读(4461)  评论(0)    收藏  举报