December 25, 2011

Code to Create Zip file and Download using DotNetZip Library

Below is the code to create zip file on the server and download it

first download the DotNetZip Library from the below link

http://dotnetzip.codeplex.com/

Add the reference of Ionic.zip.dll  within your application.

Add below using statements to the Program



using Ionic.Zip;
using Ionic.Zlib;
using Ionic.BZip2;
using System.IO;
using System.Net;



Below is the sample code to create zip files.
Dataset being passed in below method has the URL's of the files to be added in to the zip file


  public void ZIPfiles(DataSet ds,String FileName)
    {
        try
        {
            Response.Clear();
            // no buffering - allows large zip files to download as they are zipped
            Response.BufferOutput = false;
            // String ReadmeText = "Dynamic content for a readme file...\n" +
            // DateTime.Now.ToString("G");
            string archiveName = String.Format(FileName + ".zip",
                                              DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "attachment; filename=" + archiveName);

            ZipFile zip = new ZipFile();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {


                string appPath = System.AppDomain.CurrentDomain.BaseDirectory;
                //  string appPath = HttpContext.Current.Request.ApplicationPath;
                String filePath = ds.Tables[0].Rows[i]["ImageURL"].ToString().Remove(0, 1).ToString();
                // add a file entry into the zip, using content from a string
                zip.AddFile(appPath + filePath);
           
                // compress and write the output to OutputStream
            }

            zip.Save(System.AppDomain.CurrentDomain.BaseDirectory + "DateWiseOrder.zip");

            //download the above Zipped file from the server
            //String filePath1 = System.Web.HttpContext.Current.Server.MapPath("~/" +"DateWiseOrder.zip");

            //HyperLink1.NavigateUrl = Server.MapPath("~/")+"DateWiseOrder.zip";

            try
            {
                string strURL =  "DateWiseOrder.zip";
                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(strURL) + "\"");
                byte[] data = req.DownloadData(Server.MapPath(strURL));
                response.BinaryWrite(data);
                response.End();
            }
            catch (Exception ex)
            {
            }
       
        }

        catch (Exception ex)
        {


        }
   
    }

No comments:

Post a Comment