Zip and Unzip Files in C# with System.IO.Compression

.NET has built-in zip support in System.IO.Compression. ZipFile handles the common one-liners (zip a folder, extract an archive), and ZipArchive gives you control over individual entries. Both ship with .NET, so there is nothing to install.

Zip a folder and extract it

using System.IO.Compression;

ZipFile.CreateFromDirectory(@"C:\Folder1", @"C:\backup.zip");

ZipFile.ExtractToDirectory(@"C:\backup.zip", @"C:\Folder2");

CreateFromDirectory throws if backup.zip already exists, and ExtractToDirectory throws if a file it wants to write is already in the target folder. Delete the old archive first, and pass overwriteFiles: true to overwrite on extraction:

ZipFile.ExtractToDirectory(@"C:\backup.zip", @"C:\Folder2", overwriteFiles: true);

A longer overload of CreateFromDirectory sets the compression level and whether the folder itself becomes the top-level entry in the archive:

ZipFile.CreateFromDirectory(
    @"C:\Folder1", @"C:\backup.zip",
    CompressionLevel.SmallestSize,
    includeBaseDirectory: true);   // entries become Folder1/...

CompressionLevel.Optimal is the default and a good balance. SmallestSize (.NET 6 and later) squeezes a little more at a noticeably higher CPU cost, and Fastest is useful for large files that do not compress well anyway, such as images and video.

Zip a list of files

When the files are not all in one folder, open an archive in Create mode and add entries one at a time:

string[] files =
[
    @"C:\Folder1\file1.jpg",
    @"C:\Folder1\file2.txt",
    @"C:\Reports\summary.pdf"
];

using (ZipArchive zip = ZipFile.Open(@"C:\selected.zip", ZipArchiveMode.Create))
{
    foreach (string file in files)
    {
        zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
    }
}

The second argument is the name inside the archive. Using Path.GetFileName flattens everything into the root, so two files with the same name in different folders would both be added under one name; most unzip tools then show only one of them. Use a relative path such as "reports/summary.pdf" to keep a structure. Always use forward slashes in entry names: that is what the zip format specifies.

The archive’s central directory is written when the ZipArchive is disposed. Until then the file on disk is incomplete, so keep the using block.

Build a zip in memory

For a web response or an email attachment, you often do not want a temporary file. Write entries directly and keep the result in a MemoryStream:

using var buffer = new MemoryStream();

using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
{
    ZipArchiveEntry entry = zip.CreateEntry("readme.txt");
    using var writer = new StreamWriter(entry.Open());
    writer.Write("Generated at " + DateTime.UtcNow.ToString("O"));
}

byte[] zipBytes = buffer.ToArray();

Two things make this work. leaveOpen: true stops the archive from closing the MemoryStream when it is disposed. And reading buffer only after the using block ends guarantees the central directory has been written; read it inside the block and you get a corrupt zip.

In ASP.NET Core, Results.File(zipBytes, "application/zip", "export.zip") sends it to the browser.

Extract selected entries safely

To extract only some files, or to look inside an archive before extracting, open it for reading and loop over Entries:

using ZipArchive archive = ZipFile.OpenRead(@"C:\backup.zip");

string root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(@"C:\Extracted"));

foreach (ZipArchiveEntry entry in archive.Entries)
{
    if (!entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
        continue;

    string target = Path.GetFullPath(Path.Combine(root, entry.FullName));

    // Reject entries such as "../../Windows/evil.dll" (zip slip).
    if (!target.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal))
        throw new IOException($"Entry '{entry.FullName}' is outside the target folder.");

    Directory.CreateDirectory(Path.GetDirectoryName(target)!);
    entry.ExtractToFile(target, overwrite: true);
}

Entry names come from whoever created the archive. A malicious zip can contain names with .. segments or absolute paths that point outside your target folder, an attack known as zip slip. ZipFile.ExtractToDirectory checks for this itself; code that builds paths from entry.FullName must do the check, as above.

For archives from untrusted sources, also look at entry.Length (the uncompressed size) before extracting. A zip bomb is a few kilobytes compressed and many gigabytes extracted.

Password-protected zip files

System.IO.Compression cannot create or read encrypted zip files. For that you need a library. SharpZipLib handles password-protected zips, including AES encryption; set the Password property on its ZipOutputStream or ZipFile class. The original version of this post used SevenZipSharp, a wrapper around 7-Zip’s native 7z.dll; it works, but it depends on a native DLL you have to ship and load, which makes cross-platform deployment harder.

If you only need to protect the data, not produce a zip someone opens in Explorer, zip it with the built-in classes and encrypt the result with AES.

Related examples

Leave a Comment