Does .NET support Deflate compression? Yes, with DeflateStream

Posted: (EET/GMT+2)

 

If you need to use the Deflate compression algorithm in C#, use the DeflateStream class from the System.IO.Compression namespace.

The important detail is that DeflateStream works on streams. It compresses bytes as they are written, and decompresses bytes as they are read.

Here is a small example that compresses a string into a byte array:

using System.IO.Compression;
using System.Text;

string text = "Hello from DeflateStream";
byte[] input = Encoding.UTF8.GetBytes(text);

using MemoryStream compressedStream = new MemoryStream();

using (DeflateStream deflateStream =
    new DeflateStream(
        compressedStream,
        CompressionLevel.SmallestSize,
        leaveOpen: true))
{
    deflateStream.Write(input, 0, input.Length);
}

byte[] compressedBytes = compressedStream.ToArray();

Console.WriteLine($"Original size: {input.Length}");
Console.WriteLine($"Compressed size: {compressedBytes.Length}");

The leaveOpen: true parameter keeps the MemoryStream open after the DeflateStream is disposed.

To decompress the data, wrap the compressed bytes in another stream:

using MemoryStream inputStream = new MemoryStream(compressedBytes);

using DeflateStream inflater = new DeflateStream(
        inputStream, CompressionMode.Decompress);

using MemoryStream outputStream = new MemoryStream();
inflater.CopyTo(outputStream);

string decompressed = Encoding.UTF8.GetString(outputStream.ToArray());
Console.WriteLine(decompressed);

The output should match the original string:

Hello from DeflateStream

Tip: DeflateStream is not the same thing as creating a .zip file. It compresses a stream of bytes. If you need a real ZIP archive with files and entries, use ZipArchive instead (details here).

The common choices are:

  • use DeflateStream for Deflate stream compression
  • use GZipStream for gzip-compatible .gz data (docs here)
  • use ZipArchive for .zip files.

Also remember that compression does not always make data smaller. Already-compressed data such as JPEG, PNG, MP4, ZIP, or PDF files may not shrink much, and can even grow slightly.

Handy: when testing compression, compare the decompressed result to the original data. Do not depend on the compressed bytes being identical across .NET versions or platforms. For normal text, JSON, XML, logs, and CSV data, Deflate can still be a useful lightweight option.

Happy data compressing!