zoukankan      html  css  js  c++  java
  • 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();
        }
      }
  • 相关阅读:
    第5章 简单的C程序设计——循环结构程序设计
    第4章 简单的C程序设计——选择结构程序设计
    通过wget工具下载指定文件中的URLs对应的资源并保存到指定的本地目录中去并进行文件完整性与可靠性校验
    Kaflka介绍
    分布式与集群
    Golang菜鸟教程day01
    优秀的github项目
    Golang教程
    windows下安装GDB
    nginx部署
  • 原文地址:https://www.cnblogs.com/refuge/p/8524555.html
Copyright © 2011-2022 走看看