-
-
Save richlander/85217d18701b74363a46cd42c22220bd to your computer and use it in GitHub Desktop.
Brotli compression and decompression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code will produce the following output: