Zip加解压字符串
一、首先下载引用“ICSharpCode.SharpZipLib.dll”
二、字符串压缩
/// <summary>
/// 将传入的二进制字符串资料以Zip算法解压缩
/// </summary>
/// <param name="zippedString">经GZip压缩后的二进制字符串</param>
/// <returns>原始未压缩字符串</returns>
public static string ZipDecompressString(this string zippedString)
{
if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
{
return "";
}
else
{
string dummyData = zippedString;
dummyData = dummyData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+").Replace("\"", "").Replace("\\n", "");
//}
byte[] b = Convert.FromBase64String(dummyData);
using (MemoryStream from = new MemoryStream(b))
using (ZipInputStream zip = new ZipInputStream(from))
using (MemoryStream to = new MemoryStream())
{
ZipEntry entry = zip.GetNextEntry();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = zip.Read(buffer, 0, buffer.Length)) > 0)
{
to.Write(buffer, 0, len);
}
b = to.ToArray();
return Encoding.UTF8.GetString(b);
}
}
}
三、压缩字符串解压
/// <summary>
/// 将传入字符串以Zip算法压缩后,返回utf-8格式Base64编码字符
/// </summary>
/// <param name="rawString">需要压缩的字符串</param>
/// <returns>压缩后的Base64编码的字符串</returns>
public static string ZipCompressString(this string rawString)
{
if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
{
return "";
}
else
{
byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString);
using (MemoryStream to = new MemoryStream())
using (ZipOutputStream zip = new ZipOutputStream(to))
{
ZipEntry entry = new ZipEntry("ToBase64String");
zip.PutNextEntry(entry);
zip.Write(rawData, 0, rawData.Length);
zip.CloseEntry(); // 必须,否则报不可预料的压缩文件末端
zip.Finish(); // 必须,否则报这个压缩文件格式未知或者数据已经被损坏
return Convert.ToBase64String(to.ToArray());
}
}
}

浙公网安备 33010602011771号