MOHAMED JACKARIAH

MOHAMED JACKARIAH

  • 1.5k
  • 178
  • 32.3k

Zipping multiple files using System.IO.Compression and downl

Jul 18 2014 6:09 AM
Using the System.IO.Compression I can Create the ZIP Archive file and my files into the ZIP archive.

After I downloaded the created ZIP Archive file is not opening. The following is the Code I am using in my application.

In the Page Load I added the files into the CheckBox List
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
// Get the list of files into the CheckBoxList
var dirInfo = new DirectoryInfo(Server.MapPath("~/DownloadLibrary/"));

chkFiles.DataSource = dirInfo.GetFiles();
chkFiles.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
Files are downloaded successfully as a ZIP file. But I can't Extract the ZIP file.
The following code for download
protected void btnDownloadNow_Click(object sender, EventArgs e)
{
try
{
string downloadFileName = string.Format("YourDownload-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
using (var zipToOpen = new MemoryStream())
{
using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
foreach (ListItem item in chkFiles.Items)
{
if (item.Selected)
{
var demoFile = archive.CreateEntry(Path.GetFileName(item.Value));

using (var entryStream = demoFile.Open())
{
var data = File.ReadAllBytes(item.Value);
entryStream.Write(data, 0, data.Length);
}
}
}

Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Response.BinaryWrite(zipToOpen.ToArray());
}
}
}
catch (Exception ex)
{

throw ex;
}
Response.End();
}