• GZip 压缩及解压缩


    /// <summary>
      /// GZipHelper 
      /// </summary>
      public class GZipHelper
      {
        /// <summary>
        /// 将传入字符串以GZip算法压缩后,返回Base64编码字符
        /// </summary>
        /// <param name="rawString">需要压缩的字符串</param>
        /// <returns>
        /// 压缩后的Base64编码的字符串
        /// </returns>
        public static string GZipCompressString(string rawString)
        {
          if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            return "";
          return Convert.ToBase64String(GZipHelper.Compress(Encoding.UTF8.GetBytes(rawString.ToString())));
        }
    
        /// <summary>
        /// GZip压缩
        /// </summary>
        /// <param name="rawData"/>
        /// <returns/>
        private static byte[] Compress(byte[] rawData)
        {
          MemoryStream memoryStream = new MemoryStream();
          int num1 = 1;
          int num2 = 1;
          GZipStream gzipStream = new GZipStream((Stream) memoryStream, (CompressionMode) num1, num2 != 0);
          byte[] buffer = rawData;
          int offset = 0;
          int length = rawData.Length;
          gzipStream.Write(buffer, offset, length);
          gzipStream.Close();
          return memoryStream.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 "";
          return Encoding.UTF8.GetString(GZipHelper.Decompress(Convert.FromBase64String(zippedString.ToString())));
        }
    
        /// <summary>
        /// GZIP解压 
        /// </summary>
        /// <param name="zippedData"/>
        /// <returns/>
        public static byte[] Decompress(byte[] zippedData)
        {
          GZipStream gzipStream = new GZipStream((Stream) new MemoryStream(zippedData), CompressionMode.Decompress);
          MemoryStream memoryStream = new MemoryStream();
          byte[] buffer = new byte[1024];
          while (true)
          {
            int count = gzipStream.Read(buffer, 0, buffer.Length);
            if (count > 0)
              memoryStream.Write(buffer, 0, count);
            else
              break;
          }
          gzipStream.Close();
          return memoryStream.ToArray();
        }
      }
  • 相关阅读:
    网线
    第19次实验
    矩阵乘法
    20次试验
    视频笔记
    1
    effective C++ 条款 34:区分接口继承和实现继承
    effective C++ 条款 35:考虑virtual函数以外的其他选择
    effective C++ 条款 29:为“异常安全”而努力是值得的
    effective C++ 条款 27:尽量少做转型动作
  • 原文地址:https://www.cnblogs.com/refuge/p/8524555.html
Copyright © 2020-2023  润新知