Compress a folder of files to a ZIP archive with .NET

Compress a folder of files to a ZIP archive with .NET

When working with .NET apps you may sometimes need to bundle multiple files into a single compressed archive for easier storage, transfer, or processing. In this post, I’ll show you a simple and effective way to compress a folder into a .zip file using just a few lines of code with the built-in .NET namespace System.IO.Compression.

Why Compress a Folder?

Compressing files reduces their size, which can help save disk space, reduce network transfer time, and consolidate multiple files into a single package. ZIP files are especially convenient as they can be opened natively by most operating systems without any additional software.

namespace BenjaminAbt.ZipFileSample;

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

class Program
{
    static void Main()
    {
        // folder of files
        string sourceFolder = @"C:\ben\path\to\your\folder"; // Path to the folder you want to compress

        // fullname of zip file to write
        string destinationZipFile = @"C:\ben\path\to\your\compressedFolder.zip";

        CompressFolder(sourceFolder, destinationZipFile);
        Console.WriteLine("Folder compressed successfully!");
    }

    static void CompressFolder(string sourceFolder, string destinationZipFile)
    {
        if (File.Exists(destinationZipFile))
        {
            File.Delete(destinationZipFile); // Remove existing ZIP file if it exists
        }

        ZipFile.CreateFromDirectory(sourceFolder, destinationZipFile, CompressionLevel.Optimal, includeBaseDirectory: true);
    }
}

How It Works

  • Set the Folder Paths: Define the source folder you want to compress and the destination for the .zip file.
  • Delete Existing ZIP Files: The code checks if the destination .zip file already exists and deletes it to prevent conflicts.
  • Compress the Folder: Using ZipFile.CreateFromDirectory, the code compresses the specified folder, including its base directory, with optimal compression settings.