using System; using System.Data; using System.IO; using System.IO.Compression; namespace CK.SCP.Utils { public class GzipHelper { /// /// 解压 /// /// /// public static DataSet GetDatasetByString(string Value) { DataSet ds = new DataSet(); string CC = GZipDecompressString(Value); System.IO.StringReader Sr = new StringReader(CC); ds.ReadXml(Sr); return ds; } /// /// 根据DATASET压缩字符串 /// /// /// public static string GetStringByDataset(string ds) { return GZipCompressString(ds); } /// /// 将传入字符串以GZip算法压缩后,返回Base64编码字符 /// /// 需要压缩的字符串 /// 压缩后的Base64编码的字符串 public static string GZipCompressString(string rawString) { if (string.IsNullOrEmpty(rawString) || rawString.Length == 0) { return ""; } else { byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString()); byte[] zippedData = Compress(rawData); return (string)(Convert.ToBase64String(zippedData)); } } /// /// GZip压缩 /// /// /// static byte[] Compress(byte[] rawData) { MemoryStream ms = new MemoryStream(); GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); compressedzipStream.Write(rawData, 0, rawData.Length); compressedzipStream.Close(); return ms.ToArray(); } /// /// 将传入的二进制字符串资料以GZip算法解压缩 /// /// 经GZip压缩后的二进制字符串 /// 原始未压缩字符串 public static string GZipDecompressString(string zippedString) { if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0) { return ""; } else { byte[] zippedData = Convert.FromBase64String(zippedString.ToString()); return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData))); } } /// /// ZIP解压 /// /// /// public static byte[] Decompress(byte[] zippedData) { MemoryStream ms = new MemoryStream(zippedData); GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress); MemoryStream outBuffer = new MemoryStream(); byte[] block = new byte[1024]; while (true) { int bytesRead = compressedzipStream.Read(block, 0, block.Length); if (bytesRead <= 0) break; else outBuffer.Write(block, 0, bytesRead); } compressedzipStream.Close(); return outBuffer.ToArray(); } } }