Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Compress & Zip Files using DotNetZip

4.83/5 (3 votes)
23 Jul 2018CPOL1 min read 17.3K  
How to compress and zip files using DotNetZip

Introduction

Have you ever encountered a scenario when you have to download few files zipped and compressed! Some types of development 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

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 being created on the fly (a PDF using rotativa) is saved in the same folder and zipped.

File Created on the Fly Using Rotativa

C#
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 is generating a PDF using a cshtml Razor view page using Rotativa.

It is best to follow this article for more information on how to generate PDF using Rotativa using MVC.
Let's look at the code snippet for the zipping.

C#
using (ZipFile zipFile = new ZipFile())
                {                    
                    //Get all filepath from folder
                    String[] files = Directory.GetFiles(Server.MapPath("/"));
                    string fileUniqueName = "Template"
                    memoRefCode = memoRefCode.Replace('/', '_');
                    foreach (string file in files)
                    {
                        if (file.Contains(memoID.ToString()))
                        {
                            zipFile.AddFile(file, @"MemoDocs_"+ memoRefCode); //Adding files 
                                                                    //from filepath into Zip          
                        }
                    }

                    Response.ClearContent();
                    Response.ClearHeaders();

                    //Set zip file name
                    Response.AppendHeader
                       ("content-disposition", "attachment; filename=MemoDocuments.zip");
                    zipFile.CompressionMethod = CompressionMethod.BZip2;
                    zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                    //Save the zip content in 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(memoID.ToString()))
                    {
                        FileInfo fi = new FileInfo(file);
                        fi.Delete();
                    }
                }
                //Dispense the stream
                return new FileStreamResult(outputStream, fileType);

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)