Upload a File and Then Create Zip File in .NET 4.5

Introduction

 
This article explains how to upload a file and then create a Zip File.
 
Step 1
 
In the sample application, we will use "Ionic.Zip.dll" available in the "DotNetZip Library", you need to download it from this link: Download DotNetZip Developer's Kit.
 
After downloading it Unzip it so that the various libraries are available.
 
Now create a new application in Visual Studio 2012.
 
Right-click on your application and then click on "Add reference".
 
zip 1.jpg
 
Step 2
 
Now in the Reference Manager Wizard click on the Browse button to add the reference from the folder where the DotNetZip Library is stored.
 
zip 2.jpg
 
Browse to the Ionic.Zip.dll and then click on the Add button, this will add this DLL file to your project.
 
zip 3.jpg
 
Step 3
 
Now we will add a File Upload, a Label, and a Button to our application.
  1. <asp:FileUpload ID="fileupload" runat="server" />  
  2. <asp:Button ID="createzip" Text="ZipFile" runat="server" OnClick="createzip_Click" />  
  3. <asp:Label ID="Label1" runat="server" ForeColor="#CC0000" /> 
After adding these, add a new folder to the application and name it "ZipFolder", this will be the folder where all the Zip Files will be stored.
 
Step 4
 
Now add the "System.IO" assembly to your application and then add the following code to the "aspx.cs" file of your application.
  1. if (fileupload.HasFile)  
  2. {  
  3.     string zipfilepath = Server.MapPath("~/ZipFolder/" + Path.GetFileName(fileupload.PostedFile.FileName));  
  4.     fileupload.SaveAs(zipfilepath);  
  5.     string secondPath = Server.MapPath("~/ZipFolder/");  
  6.     string[] x = Directory.GetFiles(secondPath);  
  7.     using (Ionic.Zip.ZipFile compress = new Ionic.Zip.ZipFile())  
  8.     {  
  9.         string dateofcreation = DateTime.Now.ToString("y");  
  10.         dateofcreation = dateofcreation.Replace("/""");  
  11.         compress.AddFiles(x, dateofcreation);  
  12.         compress.Save(Server.MapPath(dateofcreation + ".zip"));  
  13.         Label1.Text = "ZIP Created Successfully";  
  14.     }  
  15.     if (Label1.Text == "ZIP Created Successfully")  
  16.     {  
  17.         Array.ForEach(Directory.GetFiles(secondPath),  
  18.           delegate(string deleteFile) { File.Delete(deleteFile); });  
  19.     }  

This code will first check if there is a file for uploading; if there is then it will add the file to the Zip Folder. For naming the file it will check the system's current date and will add ".Zip" as its extension. After creating the Zip File it will give you the Message "Zip Created Successfully".
 
Output
 
First, no file is chosen so it will show that No File is chosen.
 
zip 4.jpg
 
Click on the "Choose File" button and browse to the file that you want to add as a Zip file.
 
zip 5.jpg
 
After that click on the ZipFile Button, if it is converted then it will show "Zip Created Successfully".
 
zip 6.jpg