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.

 1namespace BenjaminAbt.ZipFileSample;
 2
 3using System;
 4using System.IO;
 5using System.IO.Compression;
 6
 7class Program
 8{
 9    static void Main()
10    {
11        // folder of files
12        string sourceFolder = @"C:\ben\path\to\your\folder"; // Path to the folder you want to compress
13
14        // fullname of zip file to write
15        string destinationZipFile = @"C:\ben\path\to\your\compressedFolder.zip";
16
17        CompressFolder(sourceFolder, destinationZipFile);
18        Console.WriteLine("Folder compressed successfully!");
19    }
20
21    static void CompressFolder(string sourceFolder, string destinationZipFile)
22    {
23        if (File.Exists(destinationZipFile))
24        {
25            File.Delete(destinationZipFile); // Remove existing ZIP file if it exists
26        }
27
28        ZipFile.CreateFromDirectory(sourceFolder, destinationZipFile, CompressionLevel.Optimal, includeBaseDirectory: true);
29    }
30}

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.

Comments

Twitter Facebook LinkedIn WhatsApp