/// /// 將傳入字元串以GZip演算法壓縮後,返回Base64編碼字元 /// /// 需要壓縮的字元串 /// 壓縮後的Base64編碼的字元串 public string GZipCompressString(string rawString) { ... ...
/// <summary> /// 將傳入字元串以GZip演算法壓縮後,返回Base64編碼字元 /// </summary> /// <param name="rawString">需要壓縮的字元串</param> /// <returns>壓縮後的Base64編碼的字元串</returns> public 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)); } } /// <summary> /// GZip壓縮 /// </summary> /// <param name="rawData"></param> /// <returns></returns> 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(); } /// <summary> /// 將傳入的二進位字元串資料以GZip演算法解壓縮 /// </summary> /// <param name="zippedString">經GZip壓縮後的二進位字元串</param> /// <returns>原始未壓縮字元串</returns> public static string GZipDecompressString(string zippedString) { if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0) { return ""; } else { byte[] zippedData = Convert.FromBase64String(zippedString.ToString()); using (var ms = new MemoryStream(zippedData)) { using (var zip = new GZipStream(ms, CompressionMode.Decompress)) { using (var reader = new StreamReader(zip)) { return reader.ReadToEnd(); } } } } }