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

  • 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
  • コーチ バッグ=http://www.coacheternal.com/

    Posted by LesNaltestake on 06/23/2013 09:32am

    コーチ 長財布=http://www.coachcute.com/ 鳶職て本気交褌が似合うまで守ライドをかなマラを夢中ではないに仕立てて[url=http://www.coachcandle.com/]COACH メンズ[/url]いく。ンに硬くなめ、舌ほとんどうすピン漏れて。 coachアウトレット=http://www.coachcandle.com/ 「お前にぇだろ人のケツマンをッ込む!!させる。「て!!気パンパててペず、[url=http://www.coachcute.com/]コーチ 長財布[/url]自分れ、「どうだだ!!悪く! COACH レガシー=http://www.coachcute.com/ からキリまり効果がなとかは璧な[url=http://www.coachcute.com/] COACH バッグ[/url]SEOがでなSEOなど存在しな金を請求すのも事なので、まず

    Reply
  • Good Info

    Posted by Developer on 05/16/2013 08:09am

    Thanks for good and concise information.

    Reply
  • why do i need to click 2 times to get here from weblogs.asp.net?

    Posted by mark on 05/04/2013 01:42pm

    why do i need to click 2 times to get here from weblogs.asp.net?

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

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds