備忘録

備忘録

C# GZipで圧縮、展開する

Ⅰ. はじめに

RFC 1952で定義されているGZipの圧縮と展開方法です。
マジックナンバーは「1F 8B」です。

Ⅱ. やり方

1. GZipで圧縮する

public static byte[] GZipCompress(byte[] bytes)
{
  using (var ms = new MemoryStream())
  {
    using (var gzipStream = new GZipStream(ms, CompressionLevel.Fastest))
    {
      gzipStream.Write(bytes, 0, bytes.Length);
    }
    return ms.ToArray();
  }
}

2. GZipで展開する

public static byte[] GZipDecompress(byte[] bytes)
{
  var buffer = new byte[1024];

  using (var ms = new MemoryStream())
  {
    using (var gzipStream = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress))
    {
      while(true)
      {
        var readSize = gzipStream.Read(buffer, 0, buffer.Length);
        if (readSize == 0)
        {
          break;
        }

        ms.Write(buffer, 0, readSize);
      }
    }
    return ms.ToArray();
  }
}