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. If you find yourself struggling or want to increase your knowledge of C#, consider visiting the TechRepublic Academy! 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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read