Learn how to Zip and Unzip files Programmatically using c#

Rama Sagar
Posted by in C# category on for Beginner level | Points: 250 | Views : 51282 red flag

Normally we use some third-party utility to create, open and extract Zip files. At times we may want to deal with Zip files pro-grammatically. Dot NET framework 4.5 introduces some new classes in System.IO.Compression namespace that allows us to do.Using these classes we can create new Zip files, open and modify existing Zip files and extract the contents of Zip files via code.

Introduction


This article explains how to create zip files and extract them using a windows application 

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

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

we also need to import System.IO.Compression namespace in code behind which contains class like 


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.
lets create a Windows Application as shown below




Creating a Zip file


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



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

        private void Zip_Click(object sender, EventArgs e)
        {
            DialogResult result = saveFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (isFolder)
                {
                    ZipFile.CreateFromDirectory(txtfile.Text, saveFileDialog1.FileName);
                }
                else
                {
                    string[] files = txtfile.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 has been created successfully!");
            }
        }
 


Open a Zip file and Reading Entries


As shown in the below 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.

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

Extracting a Zip File


In order to extract the contents of an existing Zip file we 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 shows how this can be done:

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

Conclusion

so far we have learn how to Zip and Unzip the Files programmatically using c#..

Reference

http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)