标签:
1 public static string CompressString(string str) 2 { 3 var compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str); 4 var compressAfterByte = Compress(compressBeforeByte); 5 string compressString = Convert.ToBase64String(compressAfterByte); 6 return compressString; 7 } 8 9 public static string DecompressString(string str) 10 { 11 var compressBeforeByte = Convert.FromBase64String(str); 12 var compressAfterByte = Decompress(compressBeforeByte); 13 string compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte); 14 return compressString; 15 } 16 17 /// <summary> 18 /// Compress 19 /// </summary> 20 /// <param name="data"></param> 21 /// <returns></returns> 22 private static byte[] Compress(byte[] data) 23 { 24 try 25 { 26 var ms = new MemoryStream(); 27 var zip = new GZipStream(ms, CompressionMode.Compress, true); 28 zip.Write(data, 0, data.Length); 29 zip.Close(); 30 var buffer = new byte[ms.Length]; 31 ms.Position = 0; 32 ms.Read(buffer, 0, buffer.Length); 33 ms.Close(); 34 return buffer; 35 36 } 37 catch (Exception e) 38 { 39 throw new Exception(e.Message); 40 } 41 } 42 43 /// <summary> 44 /// Decompress 45 /// </summary> 46 /// <param name="data"></param> 47 /// <returns></returns> 48 private static byte[] Decompress(byte[] data) 49 { 50 try 51 { 52 var ms = new MemoryStream(data); 53 var zip = new GZipStream(ms, CompressionMode.Decompress, true); 54 var msreader = new MemoryStream(); 55 var buffer = new byte[0x1000]; 56 while (true) 57 { 58 var reader = zip.Read(buffer, 0, buffer.Length); 59 if (reader <= 0) 60 { 61 break; 62 } 63 msreader.Write(buffer, 0, reader); 64 } 65 zip.Close(); 66 ms.Close(); 67 msreader.Position = 0; 68 buffer = msreader.ToArray(); 69 msreader.Close(); 70 return buffer; 71 } 72 catch (Exception e) 73 { 74 throw new Exception(e.Message); 75 } 76 }
标签:
原文地址:http://www.cnblogs.com/hzzhao/p/5264620.html