ZIP file format allows you to make an archive of a set of files and compress those files in the package. The Zip file may contain the files without any compression, just for the sake of archive. The Zip format supports many algorithms. Zip files use .zip extension and ‘application/zip’ MIME type.
There are many software and tools for creating Zip files manually. However, software developers sometimes need to create the Zip files using their code. In this post, I’ll show you how to create Zip package using .NET application. I’m going to use C# for creating the sample for this post.
Although, creating Zip files from scratch and working with related algorithms is very complex and time consuming task. However, there are some free libraries which you can use in your code. One such free library is DotNetZip library. You can download this free library from codeplex.com. This library helps you Zip and Unzip files and folders in your .NET code. You can use this library in a variety of .NET applications.
In order to create a Zip file, you need to find the Ionic.Zip DLL which you can find in Tools folder inside the DotNetZip package you downloaded from codeplex.com. Once you have added the reference to this DLL, use the Ionic.Zip namespace in your code as shown below:
//Ionic library to create Zip files
After that you can use the following code to Zip the files and folders into a single package:
//create ZipFile class
ZipFile zipFile = new ZipFile();
//add whole directory in the Zip package
zipFile.AddDirectory(@”C:\Files to Zip\html”,”/package/html”);
zipFile.AddDirectory(@”C:\Files to Zip\data”, “/package/data”);
//add particular file in the package
zipFile.AddFile(@”C:\Files to Zip\main.txt”,”/package/”);
//save output Zip file
AddDirectory method allows you to add a whole directory in a Zip file. First parameter is the path to the source directory and the second parameter represents the path in the Zip archive. In this example, I have mapped html and data folders from the source directory to the folders in the package directory in Zip archive. Similarly, AddFile method allows you to add a single file in the Zip package. In this case, I have added main.txt file in the root folder inside the archive.Finally, you can save the output PDF with the help of Save method of ZipFile class.
In this post, you have got an idea that how simple it is to create a Zip package in your .NET applications with the help of free Zip library. In my next post, I’ll share some other good programming tip with you guys.