Decompress a ZIP archive with .NET

Decompress a ZIP archive with .NET

Working with compressed files is common in many applications, whether you're extracting data from an archive, installing software packages, or retrieving bundled files. Thankfully, .NET finally provides an efficient, straightforward way to decompress ZIP files using the System.IO.Compression namespace. In this post, I’ll walk through a simple code snippet that you can use to decompress ZIP files in your .NET apps.

namespace BenjaminAbt.ZipFileSample;

using System;
using System.IO;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        // fullname zip file
        string zipFilePath = @"C:\ben\path\to\your\compressedFolder.zip";

        // target folder to write files of the zip archive
        string extractPath = @"C:\ben\path\to\extract\folder";

        DecompressZipFile(zipFilePath, extractPath);
        Console.WriteLine("ZIP file decompressed successfully!");
    }

    static void DecompressZipFile(string zipFilePath, string extractPath)
    {
        if (Directory.Exists(extractPath))
        {
            Directory.Delete(extractPath, recursive: true); // Delete existing directory to avoid conflicts
        }

        ZipFile.ExtractToDirectory(zipFilePath, extractPath);
    }
}

How It Works

  • Set File Paths: Define zipFilePath as the path to the ZIP file you want to decompress, and extractPath as the folder where you want the files extracted.
  • Handle Existing Directories: The snippet checks if a folder already exists at extractPath. If it does, it deletes it to prevent conflicts during decompression.
  • Decompress with ZipFile.ExtractToDirectory: The ExtractToDirectory method handles the decompression, extracting the contents of the ZIP file to the specified destination.