Brotli in .NET

Posted by Joe Enos on March 25, 2021 · 2 mins read

Brotli is a compression algorithm like GZip - it tends to have smaller compressed files at the expense of a small amount of extra time.

Implementing in .NET is just as easy as with GZip:

public class Brotli
{
public static void Compress(Stream inputStream, Stream outputStream)
{
using var gzip = new BrotliStream(outputStream, CompressionMode.Compress);
byte[] buffer = new byte[8192];
int count;
while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
gzip.Write(buffer, 0, count);
}
}

public static void Decompress(Stream inputStream, Stream outputStream)
{
using var gzip = new BrotliStream(inputStream, CompressionMode.Decompress);
byte[] buffer = new byte[8192];
int count;
while ((count = gzip.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, count);
}
}

}