---
title: "Compress and decompress gzip in C#"
url: https://recursiveai.org/onearchive/cookbook/gzip-interop/
description: "Gzip compress and decompress a byte array or stream in C#, in one call each, with output that GZipStream, gzip and every other tool reads. A complete program with OneCompress."
version: "1.0.0"
---

# Compress and decompress gzip in C#

`GZip.Compress` and `GZip.Decompress` are one call each, and the bytes are standard gzip: .NET’s `GZipStream`, the `gzip` command and browsers read them, and OneCompress reads theirs. The program below shows both directions and a CRC-32 check.

```shell
dotnet new console -o GzipDemo && cd GzipDemo
dotnet add package RecursiveAI.OneCompress --version 1.0.0
```

Put this in `Program.cs` and run `dotnet run`:

```csharp
using System.IO.Compression;
using System.Text;
using RecursiveAI.OneCompress.Checksums;
using RecursiveAI.OneCompress.Deflate;

byte[] log = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Range(0, 5000).Select(i => $"2026-10-30T12:{i % 60:D2}:00Z GET /api/items/{i % 97} 200\n")));

// OneCompress writes gzip; System.IO.Compression reads it.
byte[] gz = GZip.Compress(log, new DeflateOptions { Level = 9 });
using (var input = new GZipStream(new MemoryStream(gz), CompressionMode.Decompress))
using (var output = new MemoryStream())
{
    input.CopyTo(output);
    Console.WriteLine($"gzip level 9: {log.Length:N0} -> {gz.Length:N0} bytes; GZipStream reads it back: {output.ToArray().AsSpan().SequenceEqual(log)}");
}

// And the other way round.
var net = new MemoryStream();
using (var w = new GZipStream(net, CompressionLevel.SmallestSize, leaveOpen: true)) w.Write(log);
Console.WriteLine($"GZipStream output read by OneCompress: {GZip.Decompress(net.ToArray()).AsSpan().SequenceEqual(log)}");

// The same bytes on every machine: hash the compressed output to check.
Console.WriteLine($"CRC32 of the gzip bytes: {Crc32.Compute(gz):X8}");
```

```text
gzip level 9: 214,480 -> 16,205 bytes; GZipStream reads it back: True
GZipStream output read by OneCompress: True
CRC32 of the gzip bytes: BF755A76
```

## Limits

- **Whole buffers in memory with the one-call form.** For files that don’t fit, use the package’s stream types, described in [the Deflate encoder](https://recursiveai.org/onearchive/docs/deflate-encoder/).

## Good to know

- `GZip`, `ZLib` and `Deflate` take `DeflateOptions`: levels 0 to 12, strategies, preset dictionaries and flushes.
- The compressed bytes are the same on every platform, so a CRC32 or SHA-256 of the output is a valid cache key or test fixture. `RecursiveAI.OneCompress.Checksums` also has CRC32C, CRC64, Adler-32 and xxHash64.

Encoder choices and speeds are in [the Deflate encoder](https://recursiveai.org/onearchive/docs/deflate-encoder/) and [checksums](https://recursiveai.org/onearchive/docs/checksums/).
