
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.
1namespace BenjaminAbt.ZipFileSample;
2
3using System;
4using System.IO;
5using System.IO.Compression;
6
7class Program
8{
9 static void Main()
10 {
11 // fullname zip file
12 string zipFilePath = @"C:\ben\path\to\your\compressedFolder.zip";
13
14 // target folder to write files of the zip archive
15 string extractPath = @"C:\ben\path\to\extract\folder";
16
17 DecompressZipFile(zipFilePath, extractPath);
18 Console.WriteLine("ZIP file decompressed successfully!");
19 }
20
21 static void DecompressZipFile(string zipFilePath, string extractPath)
22 {
23 if (Directory.Exists(extractPath))
24 {
25 Directory.Delete(extractPath, recursive: true); // Delete existing directory to avoid conflicts
26 }
27
28 ZipFile.ExtractToDirectory(zipFilePath, extractPath);
29 }
30}
How It Works
- Set File Paths: Define zipFilePath as the path to the ZIP file you want to decompress, and
extractPathas 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.

Comments