joriszwart.nl

Data compression

Minimal ZIP file – part II

This article is part of a series.

  1. Creating a valid ZIP-file
  2. Use .NET’s DeflateStream 👈 here we are
  3. No dependencies (coding the DEFLATE algorithm)

Introduction

In part 1 a valid ZIP-file was created using uncompressed data. To be more useful, data should be compressed.

The most simple way is the so-called DEFLATE algorithm1. DEFLATE is supported back to PKZIP 2.x.

Compressing the data

Using .NET’s DeflateStream it is easy to compress the data to a MemoryStream2.

It takes only a few lines:

// Compress the data
using var outputStream = new MemoryStream();
using (var deflateStream = new DeflateStream(outputStream, CompressionMode.Compress))
{
    deflateStream.Write(filedata);
}
var data = outputStream.ToArray();

Other than that, only a few modifications are needed to the headers:

Source code

The modified code:

Zip2.cs


  1. en.wikipedia.org/wiki/Deflate ↩︎

  2. Ideally, write to the zip-stream directly, but that introduces chicken’n’egg issues since the compressed size is needed to write the file header and the directory↩︎

Related