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 the Visual Studio 2012.
Right-click on your application and then click on "Add reference".
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.
Browse to the Ionic.Zip.dll and then click on the Add Button, this will add this DLL file to your project.
Step 3
Now we will add a File Upload, a Label and a Button to our application.
<asp:FileUpload ID="fileupload" runat="server" />
<asp:Button ID="createzip" Text="ZipFile" runat="server" OnClick="createzip_Click" />
<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.
if (fileupload.HasFile)
{
string zipfilepath = Server.MapPath("~/ZipFolder/" + Path.GetFileName(fileupload.PostedFile.FileName));
fileupload.SaveAs(zipfilepath);
string secondPath = Server.MapPath("~/ZipFolder/");
string[] x = Directory.GetFiles(secondPath);
using (Ionic.Zip.ZipFile compress = new Ionic.Zip.ZipFile())
{
string dateofcreation = DateTime.Now.ToString("y");
dateofcreation = dateofcreation.Replace("/", "");
compress.AddFiles(x, dateofcreation);
compress.Save(Server.MapPath(dateofcreation + ".zip"));
Label1.Text = "ZIP Created Successfully";
}
if (Label1.Text == "ZIP Created Successfully")
{
Array.ForEach(Directory.GetFiles(secondPath),
delegate(string deleteFile) { File.Delete(deleteFile); });
}
}
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 it's 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.
Click on the "Choose File" button and browse to the file that you want to add as a Zip file.
After that click on the ZipFile Button, if it is converted then it will show "Zip Created Successfully".