Using .NET Built In ZIP Support

I’ve been working at home on a project that uses ZIP files to transfer files to and from a server for storage and backup. Initially when I started this project, I installed the venerable DotNetZip library. This worked well for the initial phase of development. I could easily zip and extract the files from a background thread and it ran smoothly and efficiently.

Eventually I ran into trouble when I was working on a specific scenario where I had a Quickbooks file inside of the ZIP file. The extraction would run properly, but Quickbooks could never open the file after the extraction. I would extract the Quickbooks file using DotNetZip, 7-zip, and the built in Windows file compression, but the file always came out corrupted.

I did some more research, and discovered that starting in .NET Framework 4.5, ZIP file support is built into the .NET Framework. Since the project was still relatively small, I was able to quickly switch to use the built in class: System.IO.Compress.ZipFile

The class is very straightforward. The following code creates a ZIP file from a directory:

System.IO.Compression.ZipFile.CreateFromDirectory(folderWithFilesToZip, zipFilePath);

And a similar line of code will extract the contents of the ZIP file:

System.IO.Compression.ZipFile.ExtractToDirectory(zipFilePath, folderToExtractFilesTo);

I have run in to some small issues with this. It does not handle overwriting files if they already exist in the ZIP files. I currently handle this by simply deleting all existing files and restoring them all from the ZIP file. This works in my situation, because I am certain that all the files I will need are inside the ZIP file.

If you are unable to perform this brute force approach, you may need to check which files would be overwritten and then delete those.

Written on December 19th, 2014 by Dan Walker
Tags: c#, compression.

Want to read more?

If you’ve enjoyed what you’ve seen so far, you might like some of my other posts. Visit the archive to see all of my past writings.

Blog Archive »

About the Author

Dan Walker is a programmer from Grand Rapids, MI. He works at Gordon Food Service.

More About Dan »

Get in touch