Minimal ZIP file – part II
This article is part of a series.
- Creating a valid ZIP-file
- Use .NET’s
DeflateStream👈 - No dependencies (coding the DEFLATE algorithm)
- Calculating the CRC-32
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. I consider this
a little bit of cheating, but it is a good starting point2. See also the next part to fix this.
It takes only a few modifications to our previous program to compress the data
to a MemoryStream3 and write it to the ZIP-file:
var filedata = "BANANABANANABANANABANANABANANA"u8.ToArray();// ...// Compress the datausing var outputStream = new MemoryStream();using (var deflateStream = new DeflateStream(outputStream, CompressionLevel.Optimal)){deflateStream.Write(filedata);}var data = outputStream.ToArray();
Other than that, only a few modifications are needed when writing the headers:
- uncompressed size vs. compressed size
- compression method none vs. DEFLATE
Source code
The modified code:
Next up
In the next part the dependency on System.IO.Compression.DeflateStream will be removed.