Pages

Monday, August 19, 2013

How to Upload and Create Zip File in Asp.net

In previous article we discussed how to download and upload file in asp.net. But in this article we are explaining how to upload a file and create zip file in Asp.net. To upload and create zip file we have to use Inoc.Zip.dll from DotNetZip library and add two namespace 'Ionic.Zip' and 'System.IO'.

Step 1
Download 'Inoc.Zip.dll' from this link.


Step 2
In 'Default.aspx' add following control.

<form id="form1" runat="server">
    <div>
   
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save and Zip" />
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </form>

Step 3
Open 'Default.aspx.cs' page and write following code on button click.

protected void Button1_Click(object sender, EventArgs e)
    {
        string FilePath = string.Empty;
        try
        {
            if (FileUpload1.HasFile)
            {
                FilePath = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/") + FilePath);

                using (ZipFile zipfile = new ZipFile())
                {
                    zipfile.AddFile(FilePath);

                    zipfile.Save(Server.MapPath("~/") + FilePath);
                }

                Response.Write("File sucessfully uploaded and ziped");
                File.Delete(FilePath);
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error in file uploading");
        }
        finally
        {
            FilePath = string.Empty;
        }
    }

Step 4

Finally run project and click on 'Upload File' to upload file and click on 'Save and Zip' to save and zip.

No comments:

Post a Comment