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 /// <summary> 14 /// 解壓 15 /// </summary> 16 /// <param name="Value"></param> 17 /// <returns></returns> 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 /// <summary> 27 /// 根據DATASET壓縮字符串 28 /// </summary> 29 /// <param name="ds"></param> 30 /// <returns></returns> 31 public static string GetStringByDataset(string ds) 32 { 33 return GZipCompressString(ds); 34 } 35 /// <summary> 36 /// 將傳入字符串以GZip算法壓縮後,返回Base64編碼字符 37 /// </summary> 38 /// <param name="rawString">須要壓縮的字符串</param> 39 /// <returns>壓縮後的Base64編碼的字符串</returns> 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 /// <summary> 55 /// GZip壓縮 56 /// </summary> 57 /// <param name="rawData"></param> 58 /// <returns></returns> 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 /// <summary> 68 /// 將傳入的二進制字符串資料以GZip算法解壓縮 69 /// </summary> 70 /// <param name="zippedString">經GZip壓縮後的二進制字符串</param> 71 /// <returns>原始未壓縮字符串</returns> 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 /// <summary> 85 /// ZIP解壓 86 /// </summary> 87 /// <param name="zippedData"></param> 88 /// <returns></returns> 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 }
字符串壓縮備用!算法
=================編碼