Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

GZipStream, ZipFile and compression in C#

Reference for System.IO.Compression in C#: GZipStream, DeflateStream, BrotliStream, ZipFile, ZipArchive, compression levels and safe extraction.

The System.IO.Compression namespace compresses data without any extra packages. There are two families. The stream classes GZipStream, DeflateStream, ZLibStream and BrotliStream wrap another stream and compress or decompress the bytes that pass through. The archive classes ZipFile and ZipArchive work with .zip files that hold many named entries.

A compression stream is a decorator: when you create it with CompressionMode.Compress and write to it, compressed bytes go to the inner stream; with CompressionMode.Decompress and read from it, you get the original bytes back. You must dispose the compressing stream (or call Flush and dispose) so the trailer is written, otherwise the output is truncated.

C#
using var output = File.Create("data.gz");
using var gzip = new GZipStream(output, CompressionLevel.Optimal);
gzip.Write(bytes);

Try it

C# Compress and decompress 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.

C# Creating and reading a zip archive

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.

Syntax

C#
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen = false);
public GZipStream(Stream stream, CompressionLevel level, bool leaveOpen = false);
// DeflateStream, ZLibStream and BrotliStream have the same constructors

public static void ZipFile.CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName);
public static void ZipFile.ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName);
public static ZipArchive ZipFile.OpenRead(string archiveFileName);
public static ZipArchive ZipFile.Open(string archiveFileName, ZipArchiveMode mode);
Name Description
stream The inner stream: the destination when compressing, the source when decompressing.
mode CompressionMode.Compress or Decompress. Giving a CompressionLevel instead means "compress".
level Optimal (default), Fastest, NoCompression or SmallestSize.
leaveOpen If true, disposing the compression stream does not close the inner stream.
ZipArchiveMode Read, Create or Update for ZipArchive and ZipFile.Open.

Returns: the stream constructors give a stream; ZipFile.OpenRead and Open give a ZipArchive that you must dispose. ZipArchiveEntry exposes FullName, Name, Length, CompressedLength, LastWriteTime and Open().

Errors: InvalidDataException for corrupt or non-gzip input, FileNotFoundException/DirectoryNotFoundException, IOException when the destination file already exists (ExtractToDirectory overwrites only if you pass overwriteFiles: true).

Usage notes

  • Choose the format by who reads it. GZip (.gz, HTTP Content-Encoding: gzip) is the universal single-stream format. Deflate is the raw algorithm, ZLib is deflate with a small header and checksum, and Brotli usually compresses text better and is common for web assets. A zip is the one to pick when several named files travel together.
  • Dispose before reading the result. The final bytes of a compressed stream are written on Dispose. Reading MemoryStream.ToArray() while the GZipStream is still open gives a truncated, undecodable result.
  • leaveOpen. By default the inner stream is closed together with the compression stream. Pass leaveOpen: true when you want to keep using a MemoryStream afterwards.
  • Already compressed data does not shrink. JPEG, MP4, zip and encrypted data gain nothing and may grow slightly. Use NoCompression or skip the step.
  • Levels trade speed for size. Fastest is good for logs on the hot path, SmallestSize for archives built once. Exact byte counts vary between runtime versions, so never assert them in tests; check that decompressing returns the original.
  • Zip Slip. An entry name can contain .. segments. ZipFile.ExtractToDirectory and ZipArchiveEntry.ExtractToFile guard against writing outside the target in current .NET versions, but if you extract entries by hand, resolve the full path and check that it starts with the destination folder.
  • Zip bombs. Check entry.Length and the total before extracting untrusted archives, and cap the bytes you copy when decompressing untrusted streams.
  • Async. All stream classes support ReadAsync/WriteAsync; use await using to flush the trailer asynchronously.
  • Entry names use /. Always use forward slashes in entry names so archives open correctly on every platform.