利用SharpZipLib对字符串进行压缩和解压缩
添加对ICSharpCode.SharpZipLib的引用。
using ICSharpCode.SharpZipLib.BZip2; /// <summary> /// 压缩 /// </summary> /// <param name="text"></param> /// <returns></returns> private static string Compress(string text) { if (text.IsNullOrEmpty()) { return string.Empty; } using (MemoryStream mZipStreamIn = new MemoryStream(Encoding.UTF8.GetBytes(text))) { using (MemoryStream mZipStreamOut = new MemoryStream()) { BZip2.Compress(mZipStreamIn, mZipStreamOut, true, 5); return Convert.ToBase64String(mZipStreamOut.ToArray()); } } }
/// <summary> /// 解压缩 /// </summary> /// <param name="zipText"></param> /// <returns></returns> private static string DeCompress(string zipText) { if (zipText.IsNullOrEmpty()) { return string.Empty; } using (MemoryStream mZipStreamIn = new MemoryStream(Convert.FromBase64String(zipText))) { using (MemoryStream mZipStreamOut = new MemoryStream()) { BZip2.Decompress(mZipStreamIn, mZipStreamOut, false); return Encoding.UTF8.GetString(mZipStreamOut.ToArray()); } } }
对字符串的压缩与压缩文件一样,越大效果越明显,对很小的文件或者字符串进行压缩,得到的结果往往比压缩之前还要大