Select Page

A compression round trip has one decisive check: do the decompressed bytes equal the original bytes? This console program uses BrotliStream to answer that question for repeated text, seeded random bytes and an empty array. It also prints a size table for three compression levels, so you can inspect the result on your runtime.

The example targets .NET 10 and uses only the base class library. It reads no files and makes no network requests. Its inputs are created inside the program.

What the two streams do

A MemoryStream holds the compressed bytes; a BrotliStream wraps that buffer to encode writes. On the return trip, another wrapper uses CompressionMode.Decompress and copies decoded bytes into a fresh buffer. Microsoft documents these constructors and the stream operations in the BrotliStream API reference.

Compression operates on bytes. The repeated sentence is converted to ASCII once, then repeated to fill a 64 KiB array. A separate 64 KiB array comes from Random(305); the seed makes that input repeatable in this runtime. The third input is empty. Each input visits Fastest, Optimal and SmallestSize.

Run the complete program

Create a console project with the .NET 10 SDK, replace its entire Program.cs with the program below, and run it:

dotnet new console --framework net10.0 --name BrotliRoundTrip
cd BrotliRoundTrip
dotnet run
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

const int inputSize = 64 * 1024;
byte[] sentence = Encoding.ASCII.GetBytes("Brotli streams carry bytes, not strings. ");
byte[] repeated = new byte[inputSize];
for (int i = 0; i < repeated.Length; i++)
    repeated[i] = sentence[i % sentence.Length];
byte[] random = new byte[inputSize];
new Random(305).NextBytes(random);

(string Name, byte[] Bytes)[] inputs =
{
    ("repeated", repeated),
    ("seeded-random", random),
    ("empty", Array.Empty<byte>())
};
CompressionLevel[] levels =
{
    CompressionLevel.Fastest,
    CompressionLevel.Optimal,
    CompressionLevel.SmallestSize
};

Console.Error.WriteLine(RuntimeInformation.FrameworkDescription);
Console.Error.WriteLine("input | level | original bytes | compressed bytes");
foreach (var input in inputs)
{
    foreach (var level in levels)
    {
        using var compressed = new MemoryStream();
        using (var encoder = new BrotliStream(compressed, level, leaveOpen: true))
        {
            ExpectNotSupported(() => { _ = encoder.Length; });
            ExpectNotSupported(() => { _ = encoder.Position; });
            encoder.Write(input.Bytes, 0, input.Bytes.Length);
            encoder.Flush();
        }
        if (!compressed.CanWrite)
            throw new InvalidOperationException("leaveOpen did not preserve the buffer.");
        byte[] encoded = compressed.ToArray();

        using var source = new MemoryStream(encoded);
        using var decoder = new BrotliStream(source, CompressionMode.Decompress);
        using var restored = new MemoryStream();
        decoder.CopyTo(restored);
        bool equal = input.Bytes.SequenceEqual(restored.ToArray());

        Console.Error.WriteLine($"{input.Name} | {level} | {input.Bytes.Length} | {encoded.Length}");
        Console.WriteLine($"{input.Name}/{level}: {(equal ? "PASS" : "FAIL")}");
        if (!equal)
            throw new InvalidOperationException("Round trip changed the bytes.");
    }
}

static void ExpectNotSupported(Action action)
{
    try
    {
        action();
    }
    catch (NotSupportedException)
    {
        return;
    }
    throw new InvalidOperationException("Expected NotSupportedException.");
}

Check correctness separately from size

The size table and runtime description go to standard error; the nine verdict lines go to standard output. Both normally appear in your terminal. To keep a clean pass/fail report while saving your size measurements, run:

dotnet run > roundtrip-results.txt 2> roundtrip-sizes.txt

The expected standard output is exactly:

repeated/Fastest: PASS
repeated/Optimal: PASS
repeated/SmallestSize: PASS
seeded-random/Fastest: PASS
seeded-random/Optimal: PASS
seeded-random/SmallestSize: PASS
empty/Fastest: PASS
empty/Optimal: PASS
empty/SmallestSize: PASS

Every verdict comes from SequenceEqual on the original and restored byte arrays. A mismatch prints FAIL and throws, so an incorrect result cannot silently complete. An empty input still goes through the encoder and decoder. Inspect its compressed byte count in your table rather than assuming an empty payload has an empty compressed representation.

The level names describe priorities. Fastest favors completion speed, Optimal balances speed and size, and SmallestSize favors output size even when compression takes longer. They are preferences interpreted by the compressor, not numeric quality settings. See the CompressionLevel documentation. Compare the actual rows rather than assuming their sizes must be strictly ordered. This program measures sizes, not elapsed time, and establishes no speed ranking.

Dispose the encoder before reading the result

The inner using block matters: it ends before compressed.ToArray(). The program writes the input, calls Flush, then disposes the encoder before consuming the compressed result. The API describes flushing as writing pending encoder data. Keep disposal as part of completing the encoding operation; this example does not test consuming a still-open encoder’s output.

leaveOpen: true preserves the underlying memory buffer when the encoder is disposed. The explicit CanWrite check verifies that lifetime boundary. The outer using declaration releases that buffer at the end of the iteration. The decoder owns its source stream; the additional source declaration is harmless and makes the local lifetime explicit.

Do not read Length or Position from the Brotli wrapper to obtain compressed size or progress. Both properties throw NotSupportedException, as listed in the API property table. The example checks those exceptions while the encoder is open. It measures the resulting byte array instead. For the exception syntax, see our C# exception handling lesson. For a separate introduction to stream-based file work, see reading and writing text files.

How this relates to the October advisory

Microsoft’s October 25, 2026 out-of-band security update notice identifies a Brotli decompression vulnerability and includes the System.IO.Compression Brotli APIs among possible entry points. It states:

Request decompression and automatic response decompression are not enabled by default.

Those defaults concern the named HTTP features. This console app explicitly invokes decompression itself. A successful round trip proves byte preservation for these inputs; it does not demonstrate a vulnerability, verify a security fix or audit an application’s deployment.

The exact program above was compiled and run in an isolated .NET 10.0.13 environment with all nine expected verdicts and no compiler warnings. That is an API behavior test on that environment; the patched runtime was not tested. Consult the update notice for its version-specific update guidance. It gives this command to list installed runtimes:

dotnet --list-runtimes

The notice also explains that self-contained applications and containers carry their own runtimes and need separate checks. A host’s runtime list alone does not establish their update status.

Share This