Skip to content

Instantly share code, notes, and snippets.

@richlander
Created May 30, 2018 07:34
Show Gist options
  • Save richlander/85217d18701b74363a46cd42c22220bd to your computer and use it in GitHub Desktop.
Save richlander/85217d18701b74363a46cd42c22220bd to your computer and use it in GitHub Desktop.
Brotli compression and decompression
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Console;
namespace BrotliApp
{
class Program
{
static readonly string s_URL = "https://raw.githubusercontent.com/dotnet/core/master/README.md";
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync(s_URL,HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();
WriteLine($"Request URL: {s_URL}");
WriteLine($"Initial content length: {response.Content.Headers.ContentLength}");
var compressedStream = CompressWithBrotli(stream);
WriteLine($"Compressed content length: {compressedStream.Length}");
var decompressedStream = DecompressWithBrotli(compressedStream);
WriteLine($"Decompressed content length: {decompressedStream.Length}");
WriteLine($"Compression ratio: {100 - (Decimal.Divide(compressedStream.Length, response.Content.Headers.ContentLength.Value)*100):N1}%");
WriteLine("First 10 lines of decompressed content");
WriteLine();
var reader = new StreamReader(decompressedStream);
for (var i = 0; i < 10; i++)
{
WriteLine(reader.ReadLine());
}
}
public static Stream CompressWithBrotli(Stream toCompress)
{
MemoryStream compressedStream = new MemoryStream();
using (BrotliStream compressionStream = new BrotliStream(compressedStream, CompressionMode.Compress, leaveOpen: true))
{
toCompress.CopyTo(compressionStream);
}
compressedStream.Position = 0;
return compressedStream;
}
public static Stream DecompressWithBrotli(Stream toDecompress)
{
MemoryStream decompressedStream = new MemoryStream();
using (BrotliStream decompressionStream = new BrotliStream(toDecompress, CompressionMode.Decompress, leaveOpen: true))
{
decompressionStream.CopyTo(decompressedStream);
}
decompressedStream.Position = 0;
return decompressedStream;
}
}
}
@richlander
Copy link
Author

This code will produce the following output:

Request URL: https://raw.githubusercontent.com/dotnet/core/master/README.md
Initial content length: 2244
Compressed content length: 727
Decompressed content length: 2244
Compression ratio: 67.6%
First 10 lines of decompressed content

# .NET Core Home

The dotnet/core repository is a good starting point for .NET Core.

The latest major release is [.NET Core 2.1](release-notes/2.1/2.1.0.md). The latest patch updates are listed in [.NET Core release notes](release-notes/README.md)

## Download the latest .NET Core SDK

* [.NET Core 2.1 SDK](release-notes/download-archives/2.1.0-download.md)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment