---
title: "Compress Brotli data in C#"
url: https://recursiveai.org/onearchive/cookbook/compress-brotli-data/
description: "Compress Brotli data in C# with a free, open-source .NET library. Run the complete example, restore the result and compare its contents."
version: "1.2.0"
---

# Compress Brotli data in C#

**OneArchive** is a free, open-source archive and compression library for .NET from Recursive AI: archives (zip, tar, 7z, RAR 5, cpio, ar, ISO) in RecursiveAI.OneArchive, codecs (zlib, gzip, xz, Zstandard, Brotli) in RecursiveAI.OneCompress. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneCompress) · [GitHub](https://github.com/recursive-ai-oss/onearchive-csharp) · [Docs](https://recursiveai.org/onearchive/docs/) · [Download example (.zip)](https://recursiveai.org/onearchive/cookbook/compress-brotli-data/compress-brotli-data.zip)

Brotli compresses bytes for storage or transfer. This example uses the managed C# encoder in RecursiveAI.OneCompress and restores the bytes with its decoder.

```shell
dotnet add package RecursiveAI.OneCompress
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneCompress.Brotli;

byte[] packed = Brotli.Compress("Hello!"u8);
byte[] restored = Brotli.Decompress(packed);
Console.WriteLine(
    System.Text.Encoding.UTF8.GetString(restored));
```

```text
Hello!
```

Unzip [the example](https://recursiveai.org/onearchive/cookbook/compress-brotli-data/compress-brotli-data.zip), then `dotnet run`.

## The full program

The program generates `message.txt`: the text `Hello from Brotli!` followed by a newline, repeated 100 times. It writes `message.txt.br` and `restored.txt`, then compares the bytes. It replaces these sample files on each run.

```csharp
using RecursiveAI.OneCompress.Brotli;
using System.Text;

byte[] original = Encoding.UTF8.GetBytes(
    string.Concat(Enumerable.Repeat("Hello from Brotli!\n", 100)));
File.WriteAllBytes("message.txt", original);
byte[] packed = Brotli.Compress(original);
File.WriteAllBytes("message.txt.br", packed);
byte[] restored = Brotli.Decompress(
    File.ReadAllBytes("message.txt.br"),
    new BrotliDecompressionOptions { MaxOutputSize = 1024 * 1024 });
File.WriteAllBytes("restored.txt", restored);
Console.WriteLine($"Input: {original.Length} bytes");
Console.WriteLine($"Compressed: {packed.Length} bytes");
Console.WriteLine($"Restored: {restored.Length} bytes");
Console.WriteLine($"Bytes match: {original.SequenceEqual(restored)}");
```

`dotnet run` prints:

```text
Input: 1900 bytes
Compressed: 29 bytes
Restored: 1900 bytes
Bytes match: True
```

Invalid or truncated compressed data raises `CompressionFormatException`; exceeding a decoder limit raises `CompressionLimitException`.

## Variations

Choose quality 4, a 16-bit window and a 1 KiB output cap. Each snippet runs independently.

```csharp
using RecursiveAI.OneCompress.Brotli;

byte[] packed = Brotli.Compress("Hello!"u8,
    new BrotliOptions { Quality = 4, WindowBits = 16 });
byte[] restored = Brotli.Decompress(packed,
    new BrotliDecompressionOptions { MaxOutputSize = 1024 });
Console.WriteLine(restored.Length);
```

```text
6
```

## Related recipes

- [Compress and decompress bzip2 in C#](https://recursiveai.org/onearchive/cookbook/compress-decompress-bzip2/)
- [Compress and decompress lzip in C#](https://recursiveai.org/onearchive/cookbook/compress-decompress-lzip/)
- [Create an ISO 9660 image in C#](https://recursiveai.org/onearchive/cookbook/create-iso9660-image/)
- [Decompress a Brotli stream](https://recursiveai.org/onearchive/cookbook/decompress-brotli-stream/)

## The short answer

To compress Brotli data in C# with a managed encoder, install `RecursiveAI.OneCompress`, import `RecursiveAI.OneCompress.Brotli` and call `Brotli.Compress`. It returns a complete Brotli stream. Save the result as a `.br` file or pass it to a consumer that expects Brotli bytes. Use `Brotli.Decompress` to restore the original payload.

In .NET 10, the built-in `System.IO.Compression.BrotliStream` and `BrotliEncoder` use [native compression interop](https://github.com/dotnet/runtime/blob/v10.0.0/src/libraries/Common/src/Interop/Interop.Brotli.cs). OneCompress instead implements the codec in managed C#, with no native codec dependency.

The full example creates text locally, writes `message.txt.br`, reads it back and checks that every restored byte matches. It demonstrates payload compression, not server configuration. Writing a `.br` file does not automatically enable HTTP response compression or add HTTP headers.

## How much does Brotli compress?

There is no fixed percentage. In the program above, 1,900 bytes of repeated text become 29 bytes with the default options. That is the result for this exact input, not a promise for JSON, documents, images or arbitrary files. Compare compressed and original lengths on representative input before deciding whether to keep the compressed form.

The [encoder](https://recursiveai.org/onearchive/docs/brotli-encoder/) has two main options. `Quality` ranges from 0 through 11 and defaults to 11. `WindowBits` ranges from 10 through 24 and defaults to 22. The window determines how far back a copy can reach: at most `2^WindowBits - 16` bytes. A larger window can also increase the decoder’s memory requirement. The variation shows explicit settings rather than relying on defaults.

The encoder writes RFC 7932 streams, not the nonstandard large-window variant above 24 bits. It has an uncompressed fallback for a meta-block when the compressed representation would take more bits than the uncompressed representation. That does not guarantee the entire returned stream is smaller than the original payload: the format still needs framing. Do not overwrite an original file merely because compression succeeded.

## How do I decompress a Brotli file?

Read the `.br` file as bytes and call `Brotli.Decompress`. The full program applies `BrotliDecompressionOptions.MaxOutputSize` and writes `restored.txt` only after decoding succeeds. That ordering keeps this example from saving a partial result when the byte-buffer call rejects the input. For binary payloads, keep the restored value as bytes; only decode text when you know its original encoding.

The [decoder options](https://recursiveai.org/onearchive/docs/brotli-decoder/) separate the output cap from the window cap. Brotli streams do not carry an overall uncompressed size. The default output cap is 1 GiB. `MaxWindowSize` limits a declared window before decoding starts, and defaults to the format maximum of `2^24 - 16` bytes. Lower these settings for an application that only accepts small messages.

Unlike a file archive, this API restores one byte stream, not a collection of named entries. It does not recover a filename or choose an extraction directory. Trailing bytes are rejected by default; `AllowTrailingData` is an explicit opt-in to ignore them. Invalid or truncated data raises `CompressionFormatException`, while configured size violations raise `CompressionLimitException`. Keep the checks enabled and handle failures at the boundary where your application receives compressed data.
