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 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

  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 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.

  1. using(ZipFile zipFile = new ZipFile()) {  
  2.     //Get all file paths from the 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.             zip file.AddFile(file, @ “TemplateDocs_” + DateTime.Now);  
  8.             //Adding files from the file path 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 the 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 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,

  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 n…
  7. // distinct compression 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 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.

More Posts

GENeration INVINCIble culture

A journey has just begun to create a culture, not an organization.

INVINCIX for Start-ups

In this era of digitization, we at INVINCIX are on a mission to digitize 500+ Start-Ups during the next 2 financial year FY 2021-22 And 2022-23.

Business eXperience delivery – BXD

Direct dealing with the business definition and objective .

Focus on : Optimized investment

Continuous improvement on efficiency is a learning curve.

High operations efficiency index

Deeper understanding of each other’s working style leading to long-term benefits.

Believe and philosophy

We are committed to build a GenInvinci organization that has the ability to “Engage”, “Innovate”, “Invent” And “Excel”

Corporate responsibility

A sense of satisfaction when you touch the heart with emotion.

INVINCIANS

We will keep our feet grounded, to ensure, your head is in the cloud.

Achievers

Recognizing the outstanding Invincians

Client speak

A moment to look back the accomplishment.

Accolades

It means a lot to us.

Knowledge Corner

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Career

Join our Growing Team And Proud To Ba An INVINCIANS.

Contact us

Let's connect and find the solutions you need. Our team is ready and waiting to assist you with any questions or concerns you may have.

Business transformation and re-engineering

Digital transformation framework enables excellence in “Innovation”, “Agility” And “Responsiveness”

IT process and automation services

The existence of software industry started with automation of manual processes. The automation has evolved over a period of time and termed as “Digitalization Services”.

Software development services

AD4P Experience – Unlock the potential of IT to ensure your application is future enabled .

Product engineering

Original thinkers are rare and original ideas are precious. A product is always originated by a great idea.

Simplified consulting

Our consulting will hold your hand and be part of you, through out transformation journey.

User experience services

Clear emphasis on the experience not on the interface make us a class apart .

Quality assurance

As enterprises look to software as a source of competitive advantage, they demand quality-at speed and scale.

Data management and data science

As enterprises look to software as a source of competitive advantage, they demand quality-at speed and scale.

E-board Online

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Barcode inventory

Quick inventory management using barcodes .

Routing matrix

Cost effectiveness routing with ease of customer satisfaction.

DigiStack

Unleashing efficiency in the service industry through automation .

Vendor management system

Elevate efficiency and facilitate success with vendor management system.

Spare parts management system

Simplifying your stock validation & management process.

Agile office

“Swift and Simple” office automation

Telto

Make your service station digital

Clidok

Your doctor is a click away

Tawny

A watchdog for your digital infrastructure

White patches In black-box

Extracting meaningful data from ocean of data

Vendor management system

connecting hospitality industry smoothly

X Solutions

A mini ERP for all your need

Instablood

Connecting world via blood

Invoicedge

Simplify e-Invoicing with our secured SaaS-based APIs

Workshop calendar

Browse our workshop calendar for upcoming events and opportunities to expand your knowledge and skills.

Courses

Explore our diverse range of courses designed to cater to various interests, offering opportunities for personal and professional growth

Cuttack

Head Office
Sharadha Bhawan, Rajendra Nagar, Cuttack, Odisha 753010

Bhubaneswar

Branch Office
Plot No.353, 1st Floor, Infocity Ave, Sishu Vihar, Patia, Bhubaneswar-751024, Odisha, INDIA

Singapore

Branch Office
60 eu tong sen street #02 03 furama city center Singapore 059804

UK

Branch Office
28 Rye Croft Avenue, Twickenham, London, Tw2 6hr

Vietnam

Branch Office
02nd Floor, Saigon Paragon Building, No.3 , Nguyen Luong Bang Street, Tan Phu Ward, District 07, Ho Chi Minh City, Vietnam