Use the DotNetZip library to compress and decompress files in C#

Background

example

Normally I don’t like to require third-party libraries. I don’t know what tools you have loaded on your system and I don’t want to assume you can load new tools without creating conflicts. If third-party tools get out of synch, it can also be hard to upgrade appropriately to get them all working again.

However, this tool seems worth adding to your toolkit. The .NET Framework comes with a System.IO.Compression.GZipStream class that lets you compress and decompress files. Unfortunately it works only with GZip files (with a .gz extension) not regular .zip files. You can open these files with many other third-party tools, but the Windows operating system doesn’t let you browse them the way it does Zip files. (I don’t see the logic in providing a way to make compressed files that the operating system can’t read. Perhaps it’s a licensing issue.)

You can build true Zip files with the System.IO.Packaging namespace, but Microsoft has done a terrible job with it. It requires all sorts of strange URIs, resource and document parts, relationships, and running data through streams when you should just be able to add and remove objects. (It really seems like it was designed by someone who’s never needed to do this in real life. Possibly the same people who designed the way WPF works with bitmaps.)

Installing DotNetZip

The DotNetZip library, which is free, provides .NET managed classes that you can use from C# to compress and decompress true Zip files. This example only shows a couple of the library’s features.

To get started, download the library and unzip it. Put it somewhere you can find it easily during development because the library contains the compiled DLL that you will use.

The library includes several different versions for normal Visual Studio, compact framework, Silverlight, and so on. For normal use, you would use the normal version, which currently is in the zip-v1.9 folder. Sub-folders contain Debug and Release versions.

Using the Library

To use the library, create a new program. Open the Project menu and select Add Reference. Click the Browse tab and browse to the DotNetZip DLl that you want to use.

To add a file to an archive, create a ZipFile object representing the Zip file. Then use the ZipFile object’s AddFile method to add the file to the archive, specifying the file’s path and the relative path within the archive where the file should be placed.

To extract a file from an archive, use the ZipFile class’s Read method to open the Zip file and make a ZipFile object representing it. Now you can loop through the file’s ZipEntry objects and extract any objects that you want to recover.

Using the Example

To add a file to a Zip file, enter the Zip file’s name. Enter the name of the file you want to add to it and the relative path you want the file to have inside the Zip file. Click the Add to Archive button to add the file to the Zip file.

To extract all of the files from the Zip file, enter the directory where you want the files extracted and click Extract Archive.

This example only lets you add files to an archive and extract all of the files in the archive. DotNetZip allows you to do other things like dig through a Zip file and extract only certain files. It also has AddProgress and ExtractProgress event handlers to let you know how a long operation is progressing.

How the Example Works

The following code shows how the program adds the file to the archive. The code in the using block is all there is to actually adding the file to the archive. The rest of the code updates the display and handles exceptions.

// Add the file to the archive.
private void btnAddToArchive_Click(object sender, EventArgs e)
{
    try
    {
        using (ZipFile zip = new ZipFile(txtArchiveName.Text))
        {
            // Add the file to the Zip archive's root folder.
            zip.AddFile(txtFileName.Text, txtPathInArchive.Text);

            // Save the Zip file.
            zip.Save();
        }

        // Display the file sizes.
        FileInfo old_fi = new FileInfo(txtFileName.Text);
        lblOriginalSize.Text = old_fi.Length.ToString("#,#");
        FileInfo new_fi = new FileInfo(txtArchiveName.Text);
        lblCompressedSize.Text = new_fi.Length.ToString("#,#");

        MessageBox.Show("Done");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error adding file to archive.\n" +
            ex.Message);
    }
}

This code creates the ZipFile object representing the archive and uses its AddFile method to add the file to it.

The following code shows how the program extracts the files from the archive.

// Extract the files from the archive.
private void btnExtractArchive_Click(object sender, EventArgs e)
{
    try
    {
        using (ZipFile zip = ZipFile.Read(txtArchiveName.Text))
        {
            // Loop through the archive's files.
            foreach (ZipEntry zip_entry in zip)
            {
                zip_entry.Extract(txtExtractTo.Text);
            }
        }

        MessageBox.Show("Done");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error extracting archive.\n" +
            ex.Message);
    }
}

This code reads the Zip file and loops through its entries, calling each entry’s Extract method.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in files, system and tagged , , , , , , , , , , , , . Bookmark the permalink.

One Response to Use the DotNetZip library to compress and decompress files in C#

  1. stunning says:

    stunning

    BLOG.CSHARPHELPER.COM: Use the DotNetZip library to compress and decompress files in C#

Leave a Reply

Your email address will not be published. Required fields are marked *