Create and extract .zip files in C#
Sadly there aren’t many flexible or efficient ways to create .zip files in .NET prior to .NET 4.5. Thankfully some people took the initiative and created some very easy to use libraries for creating/extracting and updating .zip files. My two all time favourite are DotNetZip and SharpZipLib.
For this example I will be using the DotNetZip
library.
First you will need to download the library (.dll) either from http://dotnetzip.codeplex.com/ or from http://www.fluxbytes.com/?dl_name=DotNetZipLib_v1.9.1.8.rar. The file should contain quite a few libraries, so choose the one that suits your needs the most and add it as a reference in your project.
I’ve constructed two methods for this example, one suitable for creating a .zip file with any files or folders you give it as an argument and one for extracting the contents of a .zip file to any location you want.
Create .zip file method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | private void CreateZipFile(List<string> items, string destination) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { // Loop through all the items foreach (string item in items) { // If the item is a file if (System.IO.File.Exists(item)) { // Add the file in the root folder inside our zip file zip.AddFile(item,""); } // if the item is a folder else if (System.IO.Directory.Exists(item)) { // Add the folder in our zip file with the folder name as its name zip.AddDirectory(item, new System.IO.DirectoryInfo(item).Name); } } // Finally save the zip file to the destination we want zip.Save(destination); } } |
Usage:
1 2 3 4 5 6 7 8 9 10 | List<string> files = new List<string>() { @"C:\Random Folder\file 1.txt", @"C:\Random Folder\file 2.txt", @"C:\Random Folder\file 3.txt", @"C:\Random Folder\Folder 1\", @"C:\Random Folder\Folder 2\", }; CreateZipFile(files, @"c:\result.zip"); |
Extract .zip file method:
1 2 3 4 5 6 7 | private void ExtractZipFile(string zipFileLocation, string destination) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileLocation)) { zip.ExtractAll(destination); } } |
Usage:
1 | ExtractZipFile(@"c:\result.zip", @"c:\test"); |
And there you have it, just a few lines of code in order to create or extract a .zip file!
Muchas gracias por compartir!! funciono perfecto
my problem is i want to zip single file with in a folder .but not created zip file with that file anther empty zip file with same name is created
This is wonderful, thanks!!!!
Is this used as concole app, or with gui?
The above code can be used in both console and windows form applications.