備忘録

備忘録

C# GZipで圧縮、展開する

1. GZipで圧縮する

public static byte[] GZipCompress(byte[] bytes)
{
  using (MemoryStream ms = new MemoryStream())
  {
    using (GZipStream compsrsm = new GZipStream(ms, CompressionLevel.Fastest))
    {
      compsrsm.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();
  }
}