How To Create And Download Zipped Files In .NET

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 its management would require this. There are a lot of packages out in the market. Here, in this article, I would be sharing the use of DotNetZip package used to zip, unzip & compress files using C#, VB.NET, & any .NET language.

Practicality

Download the DotNetzip package from NuGet package.

Download from here.

Once downloaded, it's all set to use the DotNetzip package to start zipping the files and compressing them. For the files to be zipped, here I will be using the file path and select each file to be zipped. Here also, we will see how a file is created on the fly (a PDF using Rotativa) is saved in the same folder and zipped.

File created on the fly using Rotativa
  1. var pdfResult = new Rotativa.PartialViewAsPdf("~/Template.cshtml", model) //This is HTML that would be generated as PDF  
  2. {  
  3.     FileName = "Template.pdf"  
  4. };  
  5. var resultSet = pdfResult.BuildPdf(ControllerContext);  
  6. if (resultSet != null) {  
  7.     string path = Path.Combine(Server.MapPath(subPath));  
  8.     FileStream fs = new FileStream(path + ".pdf", FileMode.Create, FileAccess.ReadWrite);  
  9.     BinaryWriter bw = new BinaryWriter(fs);  
  10.     bw.Write(resultSet);  
  11.     bw.Close();  
  12. }  

The above code snippet is generating a PDF using a cshtml Razor View page using Rotativa Using Rotativa Best to follow the mentioned article for more information to generate PDF using Rotativa using MVC. Let's look at the code snippet for zipping.

  1. using(ZipFile zipFile = new ZipFile()) {  
  2.     //Get all filepath from folder  
  3.     String[] files = Directory.GetFiles(Server.MapPath("/"));  
  4.     string fileUniqueName = "Template"  
  5.     foreach(string file in files) {  
  6.         if (file.Contains(fileUniqueName.ToString())) {  
  7.             zipFile.AddFile(file, @ "TemplateDocs_" + DateTime.Now);  
  8.             //Adding files from filepath into Zip  
  9.         }  
  10.     }  
  11.     Response.ClearContent();  
  12.     Response.ClearHeaders();  
  13.     //Set zip file name  
  14.     Response.AppendHeader("content-disposition""attachment; filename=TemplatedDocuments.zip");  
  15.     zipFile.CompressionMethod = CompressionMethod.BZip2;  
  16.     zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;  
  17.     //Save the zip content in output stream  
  18.     zipFile.Save(outputStream);  
  19. }  
  20. //Set the cursor to start position  
  21. outputStream.Position = 0;  
  22. String[] filesToDelete = Directory.GetFiles(Server.MapPath("/"));  
  23. foreach(string file in filesToDelete) {  
  24.     if (file.Contains(fileUniqueName.ToString())) {  
  25.         FileInfo fi = new FileInfo(file);  
  26.         fi.Delete();  
  27.     }  
  28. }  
  29. 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 here is the name you set for the folder having all the files after extraction.

There are three compression levels for the ZipFile an enum which describes through code as below,

  1. //  
  2. // Summary:  
  3. // The method of compression to use for a particular ZipEntry.  
  4. //  
  5. // Remarks:  
  6. // http://www.pkware.com/documents/casestudies/APPNOTE.TXT describes a number of  
  7. // distinct cmopression methods that can be used within a zip file. DotNetZip supports  
  8. // a subset of them.  
  9. public enum CompressionMethod {  
  10.     //  
  11.     // Summary:  
  12.     // No compression at all. For COM environments, the value is 0 (zero).  
  13.     None = 0,  
  14.         //  
  15.         // Summary:  
  16.         // DEFLATE compression, as described in http://www.ietf.org/rfc/rfc1951.txt. This  
  17.         // is the "normal" compression used in zip files. For COM environments, the value  
  18.         // is 8.  
  19.         Deflate = 8,  
  20.         //  
  21.         // Summary:  
  22.         // BZip2 compression, a compression algorithm developed by Julian Seward. For COM  
  23.         // environments, the value is 12.  
  24.         BZip2 = 12  
  25. }  

The above are the three algorithms used. I personally have used only BZip2 based on 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 really handy to be used and it also provides the compression algorithms which are good to go with.