C# 压缩率最高的压缩方法deflater
/// <summary> /// 压缩算法 /// </summary> /// <param name="pBytes"></param> /// <returns></returns> public static byte[] Compress(byte[] pBytes) { MemoryStream mMemory = new MemoryStream(); Deflater mDeflater = new Deflater(Deflater.BEST_COMPRESSION); using (DeflaterOutputStream mStream = new DeflaterOutputStream(mMemory, mDeflater, 131072)) { mStream.Write(pBytes, 0, pBytes.Length); } return mMemory.ToArray(); } /// <summary> /// 解压缩算法 /// </summary> /// <param name="pBytes"></param> /// <returns></returns> public static byte[] DeCompress(byte[] pBytes) { MemoryStream mMemory = new MemoryStream(); using (InflaterInputStream mStream = new InflaterInputStream(new MemoryStream(pBytes))) { Int32 mSize; byte[] mWriteData = new byte[4096]; while (true) { mSize = mStream.Read(mWriteData, 0, mWriteData.Length); if (mSize > 0) mMemory.Write(mWriteData, 0, mSize); else break; } } return mMemory.ToArray(); }
压缩测试,适用于重复比较多的字符串,对比Zip和GZip,压缩率最高
string sourceStr = "key=中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国"; byte[] pBytes = System.Text.Encoding.UTF8.GetBytes(sourceStr); pBytes = Compress(pBytes); string result = Convert.ToBase64String(pBytes); MessageBox.Show(result.Length)