[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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



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 WPF, particularly WPF 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 use it, start a new project. In Solution Explorer, right-click on References and select Manage NuGet Packages. On the Browse tab, search for DotNetZip, click it, and then on the right click Install. I had to fiddle with this a bit to get it to install because it seemed confused about .NET Framework version. If you have problems, you may need to change the version that your project is targeting.

To make using the library easier, add this using statement:

using Ionic.Zip;

Using the Library

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.