Creating and Extracting zip files in C#
How To C Sharp

Creating and Extracting zip files in C#

Mishel Shaji
Mishel Shaji

Normally, I used some third party libraries to create or extract zip files and was not an easy task. In .NET 4.5, some new classes were added to System.Compression namespace which allows you to create and extract zip files with few lines of code.

This article explains how to create and Extract a zip file programmatically using C#. To access the classes that help you to work with zip files, first, a reference to the following DLL files should be added.

Add reference

To add these files, got to Solution Explorer -> References -> Right Click and select Add Reference -> Search for these files and select them -> Click OK.

  • System.IO.Compression.dll
  • System.IO.Compression.FileSystem.dll

Add namespace

  • using System.IO.Compression;

Creating zip file from a directory

using System;
 using System.IO.Compression;
 namespace LearnCSharp
 {
     class Program
     {      
         static void Main(string[] args)
         {
             ZipFile.CreateFromDirectory(@"G:\DirectoryToZip", @"G:\DirectoryToZip.zip");
             Console.WriteLine("Task completed");
             Console.ReadKey();
         }
     }
 }

Extracting a zip file

using System;
 using System.IO.Compression;
 namespace LearnCSharp
 {
     class Program
     {      
         static void Main(string[] args)
         {
             Console.WriteLine("Task Started");
             ZipFile.ExtractToDirectory(@"G:\DirectoryToZip.zip", @"G:\DirectoryToZip");
             Console.WriteLine("Task completed");
             Console.ReadKey();
         }
     }
 }