
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

Dec 05, 2025 · 5 min read
IMemoryCache Entry Invalidation (Manual Cache Busting)
IMemoryCache is great for speeding up expensive operations (database reads, HTTP calls, heavy computations). But many real systems need more …

Nov 08, 2025 · 8 min read
.NET 10 Release: What's New (LTS) and What to Upgrade First
.NET 10 is the next Long-Term Support (LTS) release in the .NET family. LTS matters because it’s the version many teams standardize on …

Sep 24, 2025 · 9 min read
Automatically discover tools for Azure OpenAI Realtime API
Azure now provides a unified Realtime API for low‑latency, multimodal conversations over WebRTC or WebSockets. If you’ve used the earlier …
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.

Comments