Monday, April 2, 2012

Creating ZIP and UNZIP files in ASP.NET using DotNetZip library.

DotNetZip is easy to use free class library for ziping and extracing the zip files.
Check this DotNetZip for more information.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ionic.Zlib;
using Ionic.Zip;
using System.IO;




namespace ZipFilesAspDotnet
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        #region Download ZIP File
        private void DownloadFile()
        {
            if (FileUpload1.HasFile)
            {
                //file upload folder App_Data
                string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);
                string[] _zip_fileName = _fileName.ToString().Split('.');
                Response.Clear();
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + "download_" + _zip_fileName.ToString() + ".zip");

                using (ZipFile zip = new ZipFile())
                {
                    zip.AddEntry(_fileName.ToString(), File.ReadAllBytes(Server.MapPath("~/App_Data/" + _fileName.ToString())));
                    zip.Save(Response.OutputStream);
                }
            }

        }
        #endregion

        #region EXTRACT THE ZIP FILE
        private void ExtractZipFile() 
        {
            string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);

            using (ZipFile zip1 = ZipFile.Read(Server.MapPath("~/App_Data/" + _fileName.ToString())))
            {
                
                foreach (ZipEntry e in zip1)
                {
                    //destination folder zipfiles
                    e.Extract(Server.MapPath("~/ZipFiles/"), ExtractExistingFileAction.OverwriteSilently);
                }
            }

        }
        #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {
            DownloadFile();

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            ExtractZipFile();
        }
    }
}







Download Sample

2 comments:

  1. Great post.DotNetZip is the so far best library to work with zip files in dot net.Check this out for an example in windows forms application with screenshots.

    ReplyDelete
  2. But i have used same DotNet.zip file and it works only foe those zip file which has aspx pages,but it does not work for zip file which contain images.it get neither upload nor extract.so i would like to know about this that how would i extract zip file which contain images. you can also mail me on ramisaumil@yahoo.com or jarivalasaumil@gmail.com. thank you.

    ReplyDelete