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

GZip解压函数
ContractedBlock.gif View Code

GZip压缩函数
ContractedBlock.gif ExpandedBlockStart.gif 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解压函数
ContractedBlock.gif ExpandedBlockStart.gif 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压缩函数
ContractedBlock.gif ExpandedBlockStart.gif 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 }

转载于:https://www.cnblogs.com/czllfy/articles/2031918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值