Download Multiple Files As Zip File In Asp.Net
This Example Explains how to Download Multiple Files As Zip File From Server In Asp.Net.
I have placed one CheckBoxList on Aspx page to Display Files From Server And One button to download Zip Archives.
I have used DotNetZip Library to Create Zip Files from selected file(s), Add Ionic.Zip.dll in Bin folder in application root.
HTML SOURCE OF PAGE
1: <form id="form1" runat="server">
2: <div>
3: <asp:CheckBoxList ID="checkBoxList" runat="server"/>
4:
5: <asp:Button ID="btnDownload" runat="server"
6: onclick="btnDownload_Click"
7: Text="Download Files" />
8: </div>
9: </form>
C# CODE
01using System;02using System.Web.UI.WebControls;03using System.IO;04using Ionic.Zip;05 06public partial class _Default : System.Web.UI.Page 07{08 protected void Page_Load(object sender, EventArgs e)09 {10 if (!IsPostBack)11 {12 DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/www.CsharpAspNetArticles.com"));13 FileInfo[] filesInFolder = directory.GetFiles("*.*", SearchOption.AllDirectories);14 foreach (FileInfo fileInfo in filesInFolder)15 {16 checkBoxList.Items.Add(fileInfo.Name);17 }18 }19 20 }21 protected void btnDownload_Click(object sender, EventArgs e)22 {23 ZipFile multipleFiles = new ZipFile();24 Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip");25 Response.ContentType = "application/zip";26 foreach (ListItem fileName in checkBoxList.Items)27 {28 if (fileName.Selected)29 {30 string filePath = Server.MapPath("~/www.CsharpAspNetArticles.com/" + fileName.Value);31 multipleFiles.AddFile(filePath,string.Empty);32 }33 }34 multipleFiles.Save(Response.OutputStream);35 }36}VB.NET CODE
01Imports System.Web.UI.WebControls02Imports System.IO03Imports Ionic.Zip04 05Public Partial Class _Default06 Inherits System.Web.UI.Page07 Protected Sub Page_Load(sender As Object, e As EventArgs)08 If Not IsPostBack Then09 Dim directory As New DirectoryInfo(Server.MapPath("~/www.CsharpAspNetArticles.com"))10 Dim filesInFolder As FileInfo() = directory.GetFiles("*.*", SearchOption.AllDirectories)11 For Each fileInfo As FileInfo In filesInFolder12 checkBoxList.Items.Add(fileInfo.Name)13 Next14 End If15 16 End Sub17 Protected Sub btnDownload_Click(sender As Object, e As EventArgs)18 Dim multipleFiles As New ZipFile()19 Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip")20 Response.ContentType = "application/zip"21 For Each fileName As ListItem In checkBoxList.Items22 If fileName.Selected Then23 Dim filePath As String = Server.MapPath("~/www.CsharpAspNetArticles.com/" & fileName.Value)24 multipleFiles.AddFile(filePath, String.Empty)25 End If26 Next27 multipleFiles.Save(Response.OutputStream)28 End Sub29End Class.png)

0 comments: