Uploading a file and creating a Zip File in ASP.NET with C#





5.00/5 (11 votes)
Uploading a file and creating a Zip file in ASP.NET with C#.
Introduction
Here you will get to know how to generate a zip file
in ASP.NET using C#. To implement the zip file first kindly, upload the
Inoc.Zip.dll from DotNetZip library and then attach the same to the bin folder
like, go to solution explorer – click on bin – attach the Ionic.zip.dll
in the
bin folder. And create a new folder named ZipMyFiles in the current project.
Using the code
Now implement the code with the uploading file and zip files. Here you can upload any sought of file with extension .jpg, .pdf, .mp3 etc.
<asp:FileUpload ID="fuPhoto" runat="server" />
<asp:Button ID="btnZipFile" Text="ZipFile" runat="server" OnClick="btnZipFile_Click" />
<asp:Label ID="myLabel" runat="server" ForeColor="#CC0000" />
Now in code behind we implement the btnZipFile click event.Initially check whether the file upload has a file or not and save the selected file onto the temporary folder named ZipMyFiles. At the end delete all the files which were created on the ZipMyFile. If any more files exist in the ZipMyFiles folder then those files would be deleted at the end but in while creating the zip whatever files exist on that folder it would be added on to the zip file named with the current care. If again you execute the same on the same day then the previous data would be overwritten.
if (fuPhoto.HasFile)
{
string path = Server.MapPath("~/ZipMyFiles/" +
Path.GetFileName(fuPhoto.PostedFile.FileName));
fuPhoto.SaveAs(path);
string NewPath = Server.MapPath("~/ZipMyFiles/");
string[] filenames = Directory.GetFiles(NewPath);
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
string date = DateTime.Now.ToString("d");
date = date.Replace("/", "");
zip.AddFiles(filenames, date);
zip.Save(Server.MapPath(date + ".zip"));
myLabel.Text = "ZIP File Created Successfully";
}
if (myLabel.Text == "ZIP File Created Successfully")
{
Array.ForEach(Directory.GetFiles(NewPath),
delegate(string deleteFile) { File.Delete(deleteFile); });
}
}
Note: You can Zip/Upload up to 4MB by default. If you want to go with more with the size then you need to increase maxRequestLength
and exexutionTimout
in web.config - based on your requirement.
<configuration>
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="40960" />
</system.web>
</configuration>
Here I had given the execution time for processing this we had taking up to 4 minutes and the max request length with 40MB.