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();
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM