Introduction
Have you ever encountered a scenario when you have to download a few files zipped and compressed? Few developments involving the manipulation of documents and their management would require this. There are many packages out in the market. In this article, I will be sharing the use of the DotNetZip package to zip, unzip, and compress files using C#, VB.NET, and any .NET language.
Practicality
Download the DotNetzip package from the NuGet package.
Download from here.
Once downloaded, it’s set to use the DotNetzip package to start zipping and compressing the files. For the files to be zipped, here I will be using the file path and selecting each to be zipped. Here, we will also see how a file is created on the fly (a PDF using Rotativa), saved in the same folder, and zipped.
File created on the fly using Rotativa
- var pdfResult = new Rotativa.PartialViewAsPdf(“~/Template.cshtml”, model) //This is HTML that would be generated as PDF
- {
- FileName = “Template.pdf”
- };
- var resultSet = pdfResult.BuildPdf(ControllerContext);
- if (resultSet != null) {
- string path = Path.Combine(Server.MapPath(subPath));
- FileStream fs = new FileStream(path + “.pdf”, FileMode.Create, FileAccess.ReadWrite);
- BinaryWriter bw = new BinaryWriter(fs);
- bw.Write(resultSet);
- bw.Close();
- }
The above code snippet generates a PDF using a CSS and HTML Razor View page using Rotativa and Rotativa. It is best to follow the mentioned article for more information on creating a PDF using Rotativa and MVC. Let’s look at the code snippet for zipping.
- using(ZipFile zipFile = new ZipFile()) {
- //Get all file paths from the folder
- String[] files = Directory.GetFiles(Server.MapPath(“/”));
- string fileUniqueName = “Template”
- foreach(string file in files) {
- if (file.Contains(fileUniqueName.ToString())) {
- zip file.AddFile(file, @ “TemplateDocs_” + DateTime.Now);
- //Adding files from the file path into Zip
- }
- }
- Response.ClearContent();
- Response.ClearHeaders();
- //Set zip file name
- Response.AppendHeader(“content-disposition”, “attachment; filename=TemplatedDocuments.zip”);
- zipfile.CompressionMethod = CompressionMethod.BZip2;
- zipfile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
- //Save the zip content in the output stream
- zipFile.Save(outputStream);
- }
- //Set the cursor to start position
- outputStream.Position = 0;
- String[] filesToDelete = Directory.GetFiles(Server.MapPath(“/”));
- foreach(string file in filesToDelete) {
- if (file.Contains(fileUniqueName.ToString())) {
- FileInfo fi = new FileInfo(file);
- fi.Delete();
- }
- }
- return new FileStreamResult(outputStream, fileType);
The above snippet is just required to start zipping and compressing the files. As you can see, using block for the ZipFile is created with instantiation of its object.
Then, the files present under the path are navigated using Server.MapPath(“”), Once the path is set, the files if with some unique string character in the filename needs to be searched and only zipped, is set to a variable.
Then each file is looped through and added to the ZipFile object, here zipFile.AddFiles(file, ZippedFolderName); ZipFolderName is the name you set for the folder with all the files after extraction.
There are three compression levels for the ZipFile an enum which is described through code below,
- //
- // Summary:
- // The method of compression to use for a particular ZipEntry.
- //
- // Remarks:
- // http://www.pkware.com/documents/casestudies/APPNOTE.TXT describes a n…
- // distinct compression methods that can be used within a zip file. DotNetZip supports
- // a subset of them.
- public enum CompressionMethod {
- //
- // Summary:
- // No compression at all. For COM environments, the value is 0 (zero).
- None = 0,
- //
- // Summary:
- // DEFLATE compression, as described in http://www.ietf.org/rfc/rfc1951.txt. This
- // is the “normal” compression used in zip files. For COM environments, the value
- // is 8.
- Deflate = 8,
- //
- // Summary:
- // BZip2 compression, a compression algorithm developed by Julian Seward. For COM
- // environments, the value is 12.
- BZip2 = 12
- }
The above are the three algorithms used. I have used only BZip2 based on a few good reviews.
Once compressed and all files inserted into the folder, the zipped folder is ready to be downloaded using the FileStreamResult in MVC action.
Conclusion
This is the simple explanation and the code snippet for the Zip file concept. This is simple and handy to use and provides the compression algorithms that are good to go with.
Next recommended article Create Download and Open Zip File in PHP
Simple PHP function that can be used to create a ZIP file archive.