GZip 压缩及解压缩
/// <summary> /// GZipHelper /// </summary> public class GZipHelper { /// <summary> /// 将传入字符串以GZip算法压缩后,返回Base64编码字符 /// </summary> /// <param name="rawString">需要压缩的字符串</param> /// <returns> /// 压缩后的Base64编码的字符串 /// </returns> public static string GZipCompressString(string rawString) { if (string.IsNullOrEmpty(rawString) || rawString.Length == 0) return ""; return Convert.ToBase64String(GZipHelper.Compress(Encoding.UTF8.GetBytes(rawString.ToString()))); } /// <summary> /// GZip压缩 /// </summary> /// <param name="rawData"/> /// <returns/> private static byte[] Compress(byte[] rawData) { MemoryStream memoryStream = new MemoryStream(); int num1 = 1; int num2 = 1; GZipStream gzipStream = new GZipStream((Stream) memoryStream, (CompressionMode) num1, num2 != 0); byte[] buffer = rawData; int offset = 0; int length = rawData.Length; gzipStream.Write(buffer, offset, length); gzipStream.Close(); return memoryStream.ToArray(); } /// <summary> /// 将传入的二进制字符串资料以GZip算法解压缩 /// </summary> /// <param name="zippedString">经GZip压缩后的二进制字符串</param> /// <returns> /// 原始未压缩字符串 /// </returns> public static string GZipDecompressString(string zippedString) { if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0) return ""; return Encoding.UTF8.GetString(GZipHelper.Decompress(Convert.FromBase64String(zippedString.ToString()))); } /// <summary> /// GZIP解压 /// </summary> /// <param name="zippedData"/> /// <returns/> public static byte[] Decompress(byte[] zippedData) { GZipStream gzipStream = new GZipStream((Stream) new MemoryStream(zippedData), CompressionMode.Decompress); MemoryStream memoryStream = new MemoryStream(); byte[] buffer = new byte[1024]; while (true) { int count = gzipStream.Read(buffer, 0, buffer.Length); if (count > 0) memoryStream.Write(buffer, 0, count); else break; } gzipStream.Close(); return memoryStream.ToArray(); } }