Wednesday, March 6, 2013

This example explains how to Create Zip Files In Asp.Net Using C# And VB.Net. Several times while developing Asp.Net applications we need to upload files to server and Create Zip File orArchive from those uploaded files.

We can easily Create Zip Files Archives using DotNetZip 

Create a Bin Folder in solution explorer and put Ionic.Zip.dll in it.

Place one FileUpload control on aspx page and one button to upload files and create zip file in it's Click Event.

We can Delete Files From Server Or Directory After creating Zip File by writing code after calling Save() method of zipfile object,and Display Files In GridView From Server.

Create Zip File In Asp.Net 2.0,3.5,4.0


HTML SOURCE OF PAGE
   1:  <asp:FileUpload ID="fileUpload1" runat="server" />
   2:  <asp:Button ID="btnUpload" runat="server" 
   3:              onclick="btnUpload_Click" 
   4:              Text="Upload Files"/>


C# CODE
01protected void btnUpload_Click(object sender, EventArgs e)
02    {
03        if (fileUpload1.HasFile)
04        {
05            string fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
06            string fileLocation = Server.MapPath("~/UploadedFiles/" + fileName);
07            fileUpload1.SaveAs(fileLocation);
08 
09            ZipFile createZipFile = new ZipFile();
10            createZipFile.AddFile(fileLocation, string.Empty);
11            createZipFile.Save(Server.MapPath("~/CsharpAspNetArticles/CsharpAspNetArticles.zip"));
12        }  
13    }
VB.NET
01Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
02 If fileUpload1.HasFile Then
03  Dim fileName As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
04  Dim fileLocation As String = Server.MapPath("~/UploadedFiles/" & fileName)
05  fileUpload1.SaveAs(fileLocation)
06 
07  Dim createZipFile As New ZipFile()
08  createZipFile.AddFile(fileLocation, String.Empty)
09  createZipFile.Save(Server.MapPath("~/CsharpAspNetArticles/CsharpAspNetArticles.zip"))
10 End If
11End Sub

0 comments:

Post a Comment