
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.
Related articles

Aug 02, 2024 - 1 min read
Read cpu load on Windows with .NET
In C# (.NET 6 and above), there is now a very simple way to read out the CPU load with minimal overhead - i.e. without threads. The …

Jul 22, 2024 - 2 min read
.NET: the cost of returning an empty collection
Dealing with empty lists is an everyday situation in .NET. An empty list is often preferred to a null in order to control the logic. But how …

Jun 17, 2024 - 1 min read
.NET: use a preview version in your global.json
We are currently in the preview phase of .NET 9 , which releases in Nov 2024 - and if you want to test it extensively like I do, store the …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
