Zlib compression in .NET Core

I recently had the need to decompress data that had been compressed with zlib. Unfortunately the DeflateStream built in to .NET does not work with zlib streams containing a header and trailer (RFC1950).

Instead I used the excellent SharpZipLib library. It's written completely in C#, supports a number of compression formats and targets .NET Standard 2.0.

The API should feel familiar to any .NET developer and both compression and decompression took just a few lines of code:

public static Stream Decompress(byte[] data)
{
    var outputStream = new MemoryStream();
    using (var compressedStream = new MemoryStream(data))
    using (var inputStream = new InflaterInputStream(compressedStream))
    {
        inputStream.CopyTo(outputStream);
        outputStream.Position = 0;
        return outputStream;
    }
}

Ben Foster

About Me

I'm a software engineer and aspiring entrepreneur with 15 years experience in tech and have worked with companies of all sizes in areas such as healthcare, agriculture, recruitment, e-commerce and finance. I founded my first startup Fabrik in 2011.

I now head up the engineering team at Checkout.com. If you're interested in working in an exciting and innovative fin-tech company, drop me a message.

Creative Commons Licence