C# 使用GZip对字符串压缩和解压
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.IO.Compression; 7 using System.Data; 8 9 namespace Demo 10 { 11 public class ZipHelper 12 { 13 ///14 /// 解压 15 /// 16 /// 17 /// 18 public static DataSet GetDatasetByString(string Value) 19 { 20 DataSet ds = new DataSet(); 21 string CC = GZipDecompressString(Value); 22 System.IO.StringReader Sr = new StringReader(CC); 23 ds.ReadXml(Sr); 24 return ds; 25 } 26 /// 27 /// 根据DATASET压缩字符串 28 /// 29 /// 30 /// 31 public static string GetStringByDataset(string ds) 32 { 33 return GZipCompressString(ds); 34 } 35 /// 36 /// 将传入字符串以GZip算法压缩后,返回Base64编码字符 37 /// 38 /// 需要压缩的字符串 39 /// 压缩后的Base64编码的字符串 40 public static string GZipCompressString(string rawString) 41 { 42 if (string.IsNullOrEmpty(rawString) || rawString.Length == 0) 43 { 44 return ""; 45 } 46 else 47 { 48 byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString()); 49 byte[] zippedData = Compress(rawData); 50 return (string)(Convert.ToBase64String(zippedData)); 51 } 52 53 } 54 /// 55 /// GZip压缩 56 /// 57 /// 58 /// 59 public static byte[] Compress(byte[] rawData) 60 { 61 MemoryStream ms = new MemoryStream(); 62 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); 63 compressedzipStream.Write(rawData, 0, rawData.Length); 64 compressedzipStream.Close(); 65 return ms.ToArray(); 66 } 67 /// 68 /// 将传入的二进制字符串资料以GZip算法解压缩 69 /// 70 /// 经GZip压缩后的二进制字符串 71 /// 原始未压缩字符串 72 public static string GZipDecompressString(string zippedString) 73 { 74 if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0) 75 { 76 return ""; 77 } 78 else 79 { 80 byte[] zippedData = Convert.FromBase64String(zippedString.ToString()); 81 return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData))); 82 } 83 } 84 /// 85 /// ZIP解压 86 /// 87 /// 88 /// 89 public static byte[] Decompress(byte[] zippedData) 90 { 91 MemoryStream ms = new MemoryStream(zippedData); 92 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress); 93 MemoryStream outBuffer = new MemoryStream(); 94 byte[] block = new byte[1024]; 95 while (true) 96 { 97 int bytesRead = compressedzipStream.Read(block, 0, block.Length); 98 if (bytesRead <= 0) 99 break; 100 else 101 outBuffer.Write(block, 0, bytesRead); 102 } 103 compressedzipStream.Close(); 104 return outBuffer.ToArray(); 105 } 106 } 107 }
字符串压缩备用!
=================