Zip and Unzip Files Programmatically in C#

Introduction

Most of us deal with Zip files on a daily basis. Normally people use some third-party utility to create, open and extract Zip files. At times you may want to deal with Zip files programmatically. Luckily, .NET framework 4.5 introduces some new classes in System.IO.Compression namespace that allows you to do just that. Using these classes you can create new Zip files, open and modify existing Zip files and extract the contents of Zip files via code. This article examines some of these classes.

System.IO.Compression Namespace

In .NET framework 4.5 System.IO.Compression, namespaces get some new classes that allow you to work with Zip files programmatically. In order to use these classes you must refer the following two assemblies:

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

Additionally, you will also need to import System.IO.Compression namespace in your C# code files. Some of the new classes of interest are as follows:

  • ZipFile
  • ZipArchive
  • ZipArchiveEntry

The ZipFile class provides static methods for creating, opening and extracting zip files. The ZipArchive class represents a bundle of files that are compressed using Zip file format. The ZipArchiveEntry class represents a single entry from a ZipArchive. A ZipArchive typically consists of one or more ZipArchiveEntry instances.

Sample Windows Forms Application

In order to understand how to use ZipFile, ZipArchive and ZipArchiveEntry classes you will develop a Windows Forms application as shown below:

Windows Forms application

Windows Forms application

The form shown above consists of three sections - Create, Open and Extract. In order to create a new Zip file you can either select one or more files or select an entire folder. Once the file(s) or a folder is selected you will click on the Create button. Doing so will ask for a destination Zip file name and then the Zip file will be created. Clicking on the Open button allows you to select an existing Zip file. Once selected the files that make the Zip archive are shown in the ListBox. The extract button allows you to select an existing Zip file and then extract its contents to a specific folder.

Creating a Zip File

You can create Zip files in two ways - you can select one or more files and then create a Zip archive from those files or you can select a folder so as to Zip all the files it containes. The following code shows the click event handler of File, Folder and Create buttons that do this job for you.

private void button1_Click(object sender, EventArgs e)
{
  DialogResult result = openFileDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    string[] files = openFileDialog1.FileNames;
    textBox1.Text = string.Join(",", files);
    isFolder = false;
  }
}

private void button2_Click(object sender, EventArgs e)
{
  DialogResult result = folderBrowserDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    textBox1.Text = folderBrowserDialog1.SelectedPath;
    isFolder = true;
  }
}

private void button3_Click(object sender, EventArgs e)
{
  DialogResult result=saveFileDialog1.ShowDialog();
  if(result==DialogResult.OK)
  {
    if(isFolder)
    {
      ZipFile.CreateFromDirectory(textBox1.Text, saveFileDialog1.FileName);
    }
    else
   {
      string[] files=textBox1.Text.Split(',');
      ZipArchive zip = ZipFile.Open(saveFileDialog1.FileName, ZipArchiveMode.Create);
      foreach(string file in files)
      {
         zip.CreateEntryFromFile(file, Path.GetFileName(file),CompressionLevel.Optimal);
      }
      zip.Dispose();
    }
    MessageBox.Show("ZIP file created successfully!");
  }
}

As you can see the first two event handlers (button1 and button2) basically show Open File Dialog and Folder Browser Dialog respectively. Depending on whether the user selected folder or files, the isFolder variable is set to true or false so that later you can decide whether you are Zipping a set of files or an entire folder. If you select one or more files the textbox shows a comma separated list of selected files. If you select a folder the textbox shows the folder path.

Inside the click event handler of the Create button (button3) you ask the user where he wants to save the Zip file. In order to Zip all the files from a selected folder you use the CreateFromDirectory() static method of the ZipFile class. The CreateFromDirectory() method accepts two parameters, viz. the source folder path and the destination Zip file path. It then creates a Zip file at the specified location.

If you are Zipping one or more files, the Open() static method of the ZipFile class is used to create a Zip file. Notice that the second parameter of the Open() method specifies ZipArchiveMode to be Create because you are creating a new Zip file. Other possible modes are Read and Update. The CreateFromDirectory() method returns an instance of ZipArchive class. In order to add an individual file into the newly created Zip file you use the CreateEntryFromFile() method. The CreateEntryFromFile() method takes three parameters - path and name of the source file, name of the entry being added and CompressionLevel. The CompressionLevel decides whether compression is optimized for speed or size. Setting it to Optimal means maximum possible compression but the operation may take more time. Other values of CompressionLevel enumeration are Fastest and NoCompress. The Fastest level means compression speed will be faster but the compression ratio might be poor. A value of NoCompress means a file entry will be added without performing any compression.

Make sure you call the Dispose() meth of ZipArchive object, otherwise the file might be held open even after you exit the application. Although not shown in the above code it is a better practice to use using block to instantiate ZipArchive so that Dispose() method will be called automatically.

Reading Entries of a Zip File

If you need to peek inside a Zip file and get ahold of individual ZipArchiveEntry instances that make the Zip file, you can iterate through the Entries collection of a ZipArchive object. The following code shows how that can be done:

private void button4_Click(object sender, EventArgs e)
{
  DialogResult result = openFileDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    ZipArchive zip = ZipFile.OpenRead(openFileDialog1.FileName);
    listBox1.Items.Clear();
    foreach (ZipArchiveEntry entry in zip.Entries)
    {
      listBox1.Items.Add(entry.FullName);
    }
  }
}

As shown in the above code, this time the OpenRead() method of the ZipFile class is used to open an existing Zip archive for reading purposes. A foreach loop then iterates through all the entries from the Entries collection. Each entry from the Entries collection is of type ZipArchiveEntry. The FullName property of the ZipArchiveEntry class returns the full name of the entry. The full name is then added to the ListBox.

Extracting a Zip File

In order to extract the contents of an existing Zip file you use ExtractToDirectory() method of the ZipFile class. The ExtractToDirectory() method accepts two parameters - path of the source Zip file and path of the destination folder where it has to be unzipped. The following code code shows how this is done:

private void button5_Click(object sender, EventArgs e)
{
  DialogResult result = openFileDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    textBox2.Text = openFileDialog1.FileName;
    DialogResult result2 = folderBrowserDialog1.ShowDialog();
    if (result2 == DialogResult.OK)
    {
      ZipFile.ExtractToDirectory(openFileDialog1.FileName, folderBrowserDialog1.SelectedPath);
      MessageBox.Show("ZIP file extracted successfully!");
    }
  }
}

As you can see, the open file dialog allows you to select the source Zip file. The folder browser dialog allows you to select the destination folder where the file is to be unzipped.

Summary

.NET framework 4.5 introduces new classes in the System.IO.Compression namespace that allow you to work with Zip files. The main classes that you use are ZipFile, ZipArchive and ZipArchiveEntry. Using these classes you can create Zip files, open an existing Zip file and extract the contents of Zip files programmatically. These classes can be used wherever your application needs an inbuilt way of creating or extracting Zip files.



Related Articles

Downloads

Comments

  • Error while extracting 30 gb file ..please help

    Posted by Manoj on 12/04/2014 06:54am

    "Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory."

    Reply
  • Zip Password

    Posted by Swati Raut on 11/28/2014 01:23am

    This is very easy way to zip a file/folder programmatically. Can we also add password to zipped file?

    Reply
  • extracting files from folder within a zipped file

    Posted by Randy Beaman on 11/05/2014 10:40am

    I have successfully used ZipFile.ExtractToDirectory(, ) to unzip files but for the project I am working on there is a chance that the zip file could be a folder that contains files that was zipped as apposed to just a collection of files that was zipped. My application will unzip files just fine but I also need it to extract files from within a folder if that ever happens.

    Reply
  • Thanks-

    Posted by veera on 10/24/2014 03:52am

    what is the need of an isFolder = false; and True in but_2 and if condition, please update a need

    Reply
  • Usefull and to the point

    Posted by User on 09/14/2014 08:24pm

    Thanks for details.

    Reply
  • How would one delete a file from a zip file?

    Posted by Pat on 07/09/2014 02:02pm

    I need to delete a file from the zip file. I have not seen any method that would preform that operation. How would one do that? thanks

    Reply
  • Thanks a lot ..

    Posted by Sasikala on 06/04/2014 12:59am

    Thanks a lot it helped me perfectly.. great job.. please keep continuing..

    Reply
  • Programmer

    Posted by Jenika on 05/27/2014 09:45pm

    This is fine but it is possible to unzip password protected zip files?

    Reply
  • encrypt/decrypt support!

    Posted by Bassam Alugili on 07/01/2013 01:27am

    Does the new libary support Encryption/Decryption the zipped files. ~Thanks Alugili

    Reply
  • コーチ バッグ=http://www.coachcandle.com/

    Posted by Arragojonge on 06/27/2013 03:21am

    coachアウトレット=http://www.coachcute.com/ せたとしてり効果がなますぶっ璧な[url=http://www.coacheternal.com/]コーチ 長財布[/url]SEOがでうかそも存在しなないのに高のも事は自分 コーチ 斜めがけ=http://www.coachcute.com/ まとって本気交が良似合う職人!!今ライドをかな目の前ではないを己のてて[url=http://www.coacheternal.com/]COACH メンズ[/url]いく。ンに硬くなめ、舌てくれとうすピン漏れて。 コーチ 長財布=http://www.coachcandle.com/ 「お前男にぇだろじらう。鳶職ッ込む!!似た雄。「てめぇ!!力入パンパニスをず、[url=http://www.coachcute.com/]COACH メンズ[/url]自分鳶職人のだ!!わる雄た!

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds