c# Deflate压缩与解压缩函数

本文介绍了一种使用Deflate算法进行字符串压缩和解压的方法。通过C#实现,该方法可以有效地减小字符串的大小,并提供了解压功能以恢复原始数据。压缩过程采用UTF-8编码并转换为Base64格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }




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 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值