Create Zip Files Archive In Asp.Net C# VB

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 or Archive 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
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/UploadedFiles/" + fileName);
            fileUpload1.SaveAs(fileLocation);

            ZipFile createZipFile = new ZipFile();
            createZipFile.AddFile(fileLocation, string.Empty);
            createZipFile.Save(Server.MapPath("~/CsharpAspNetArticles/CsharpAspNetArticles.zip"));
        }  
    }
VB.NET
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 If fileUpload1.HasFile Then
  Dim fileName As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
  Dim fileLocation As String = Server.MapPath("~/UploadedFiles/" & fileName)
  fileUpload1.SaveAs(fileLocation)

  Dim createZipFile As New ZipFile()
  createZipFile.AddFile(fileLocation, String.Empty)
  createZipFile.Save(Server.MapPath("~/CsharpAspNetArticles/CsharpAspNetArticles.zip"))
 End If
End Sub


Download Sample Code


If you like this post than join us or share

1 comments:

Mayank Desai said...

Hi ,
I want to read data from database then create zip file and attaching zip file in email.
My all file data is storing only in database.
Could you please give me some suggestion ?


Find More Articles