Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 182 ยท Standard Library

Zip and GZip Compression

Learn C# compression with System.IO.Compression. Use GZipStream, DeflateStream and BrotliStream, compress strings and files, and create and read ZIP archives in memory.

Compression makes data smaller so it takes less disk space and less time to send over a network. Web servers compress HTML and JSON before sending it, backup tools pack folders into .zip files, and many file formats (Office documents, NuGet packages, Android apps) are really ZIP archives in disguise. The namespace System.IO.Compression gives you everything you need, with no extra packages.

There are two families of tools. Compression streams (GZipStream, DeflateStream, BrotliStream, ZLibStream) shrink a single stream of bytes. ZIP archives (ZipArchive, ZipFile) bundle many named files into one container. This lesson covers both. You should know streams and files and paths, and be comfortable with disposal.

How compression streams work

A compression stream is a wrapper around another stream. When you create it in Compress mode, everything you write is compressed and passed on to the inner stream. In Decompress mode, everything you read is pulled from the inner stream and decompressed on the fly.

flowchart LR
    A["Your data"] -->|"Write"| B["GZipStream<br/>(Compress)"]
    B --> C["Inner stream<br/>(file or memory)"]
    C -->|"Read"| D["GZipStream<br/>(Decompress)"]
    D --> E["Your data again"]

Compression streams decorate another stream, so they work with files, memory and network streams alike.

One rule trips up almost everyone: the compression stream must be disposed (or flushed and closed) before you read the output. Only then does it write the last block and the footer. If you read the inner stream too early, you get truncated, broken data.

Compressing and decompressing bytes

The helper methods below show the whole round trip in memory. We use MemoryStream as the inner stream so the examples need no files.

C# GZip round trip in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first two bytes 1F 8B are the magic number that identifies a GZip stream. The text repeats the same sentence 50 times, so it compresses extremely well. Real-world text compresses by about 60 to 80 percent. Random data and files that are already compressed (JPEG, MP4, ZIP) hardly shrink at all, and may even grow slightly.

Choosing the algorithm

Class Format Notes
GZipStream GZip (RFC 1952) The standard for .gz files and HTTP Content-Encoding: gzip
DeflateStream Raw Deflate No header or checksum; used inside other formats
ZLibStream ZLib (RFC 1950) Deflate with a small header and checksum
BrotliStream Brotli Better ratio than GZip for text; slower at the highest level; supported by browsers over HTTPS

All of them have the same API, so switching algorithms is a one-word change. CompressionLevel lets you trade speed for size: Fastest, Optimal (the default), SmallestSize and NoCompression.

C# Comparing algorithms and levels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The comparisons print booleans instead of exact byte counts because exact sizes depend on the runtime version's compression library. Never put exact compressed sizes in tests. The third argument true (leaveOpen) keeps the MemoryStream open after the compressor is disposed, so we can read its length.

Compressing files

For files you wrap the file streams instead of memory streams. Use CopyTo so that the data flows in chunks and never has to fit in memory all at once. That is the big advantage of streaming: you can compress a 10 GB log file with a few kilobytes of memory.

C#
using FileStream source = File.OpenRead("app.log");
using FileStream target = File.Create("app.log.gz");
using var gzip = new GZipStream(target, CompressionLevel.Optimal);
source.CopyTo(gzip);

Decompressing is the mirror image: open the .gz file, wrap it in a GZipStream with CompressionMode.Decompress, and CopyTo the output file. The async versions (CopyToAsync, await using) are the better choice in servers; see async and await.

Our sandbox gives each run a temporary folder, so the next example writes a real file there, compresses it and verifies the result.

C# Compress a file and read it back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ZIP archives

A ZIP file holds many files, each compressed separately, plus a directory listing at the end. System.IO.Compression.ZipArchive reads and writes them. It works on any stream, so you can create archives in memory, for example to send a download from a web endpoint without touching the disk.

You open an archive in one of three modes:

  • ZipArchiveMode.Create writes a new archive. You can only add entries.
  • ZipArchiveMode.Read opens an existing archive for reading.
  • ZipArchiveMode.Update allows both, but loads entries into memory while you edit them.
C# Create and read a ZIP in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that ZIP entry names always use forward slashes, even on Windows. entry.Name is only the file name part (readme.txt), entry.FullName is the whole path inside the archive (docs/readme.txt).

ZipFile: folders in one line

For the common job of zipping a whole directory, the static ZipFile class (same namespace) has one-line helpers:

C#
ZipFile.CreateFromDirectory("photos", "photos.zip");
ZipFile.ExtractToDirectory("photos.zip", "restored");
ZipFile.ExtractToDirectory("photos.zip", "restored", overwriteFiles: true);

Together with ZipFile.OpenRead(path) these cover most day-to-day uses. Extracting a single entry is entry.ExtractToFile(path, overwrite: true).

Zip slip: never trust entry names

An archive from the internet may contain an entry named ../../etc/passwd or ..\Windows\evil.dll. If you naively combine the entry name with your target folder, the file lands outside the target. This attack is known as zip slip. Current .NET versions of ExtractToDirectory check this for you and throw an IOException. If you extract entries manually, you must check the final path yourself.

C# A safe extraction check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The trick is Path.GetFullPath, which resolves .. segments, followed by a check that the result still starts with the root folder (with a trailing separator, so safe-root-evil does not pass as safe-root). Also consider limits against zip bombs, tiny archives that expand to gigabytes: check entry.Length and the running total before you copy.

Compression in web apps

ASP.NET Core can compress responses automatically with the response compression middleware (AddResponseCompression), which supports Brotli and GZip. Compress text formats such as HTML, JSON, CSS and JavaScript; skip images and video. On the client side, HttpClient can decompress for you if you set AutomaticDecompression on its HttpClientHandler, as described in the HttpClient lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a GZipStream used for writing be disposed before you read the compressed bytes?

    The compressor buffers data internally. Only Dispose (or Close) flushes the last block and writes the footer, so reading earlier gives truncated, invalid data.
  2. 2. Which class do you use to bundle many named files into a single compressed container?

    GZipStream, DeflateStream and BrotliStream compress one stream of bytes. ZipArchive stores many entries with names and folders in one ZIP file.
  3. 3. What is a 'zip slip' attack?

    Entry names are untrusted. If they contain .. segments and you combine them with the target folder blindly, files escape it. Resolve the full path and check it starts with the root folder.
  4. 4. What happens when you compress a JPEG image or an existing ZIP file with GZip?

    Already-compressed data has almost no redundancy left. Compressing it again wastes CPU and gains little.

Summary

  • Compression streams (GZipStream, DeflateStream, ZLibStream, BrotliStream) wrap another stream and share one API.
  • Dispose the compressor before reading its output; use leaveOpen to keep the inner stream usable.
  • Use CopyTo for files so that large data streams in small chunks.
  • ZipArchive (modes Create, Read, Update) and ZipFile handle ZIP containers; entry names use /.
  • Validate entry paths against zip slip and limit extracted sizes against zip bombs.
  • Do not recompress already compressed formats, and never test exact compressed sizes.

Next lesson: cryptography and hashing.