字符串进行压缩
压缩字符串
1 /// <summary> 2 /// 压缩操作类 3 /// </summary> 4 public static class Compression 5 { 6 /// <summary> 7 /// 对byte数组进行压缩 8 /// </summary> 9 /// <param name="data">待压缩的byte数组</param> 10 /// <returns>压缩后的byte数组</returns> 11 public static byte[] Compress(byte[] data) 12 { 13 using (MemoryStream ms = new MemoryStream()) 14 { 15 GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); 16 zip.Write(data, 0, data.Length); 17 zip.Close(); 18 byte[] buffer = new byte[ms.Length]; 19 ms.Position = 0; 20 ms.Read(buffer, 0, buffer.Length); 21 return buffer; 22 } 23 } 24 25 /// <summary> 26 /// 对byte[]数组进行解压 27 /// </summary> 28 /// <param name="data">待解压的byte数组</param> 29 /// <returns>解压后的byte数组</returns> 30 public static byte[] Decompress(byte[] data) 31 { 32 using (MemoryStream tmpMs = new MemoryStream()) 33 { 34 using (MemoryStream ms = new MemoryStream(data)) 35 { 36 GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true); 37 zip.CopyTo(tmpMs); 38 zip.Close(); 39 } 40 return tmpMs.ToArray(); 41 } 42 } 43 44 /// <summary> 45 /// 对字符串进行压缩 46 /// </summary> 47 /// <param name="value">待压缩的字符串</param> 48 /// <returns>压缩后的字符串</returns> 49 public static string Compress(string value) 50 { 51 if (string.IsNullOrEmpty(value)) 52 { 53 return string.Empty; 54 } 55 byte[] bytes = Encoding.UTF8.GetBytes(value); 56 bytes = Compress(bytes); 57 return Convert.ToBase64String(bytes); 58 } 59 60 /// <summary> 61 /// 对字符串进行解压 62 /// </summary> 63 /// <param name="value">待解压的字符串</param> 64 /// <returns>解压后的字符串</returns> 65 public static string Decompress(string value) 66 { 67 if (string.IsNullOrEmpty(value)) 68 { 69 return string.Empty; 70 } 71 byte[] bytes = Convert.FromBase64String(value); 72 bytes = Decompress(bytes); 73 return Encoding.UTF8.GetString(bytes); 74 } 75 }
Compression.Compress("hello你好666") --->"H4sIAAAAAAAEAMtIzcnJf7J3wdOle83MzAC/qg0wDgAAAA=="