Minimal ZIP file – part II
This article is part of a series.
- Creating a valid ZIP-file
- Use .NET’s
DeflateStream👈 here we are - 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 datausing 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:
- compressed size
- compression method
Source code
The modified code:
-
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. ↩︎