c# .net

asp .net download multiple files and download as zip file using c#?

asp .net download multiple files and download as zip file using c#?, someone asked me to explain?

In this article, I will show you how to download multiple files and download as zip file using c# .net. 

To achieve zip features I used third party libraries  DotNetZip. It was supported by .NET 4.5 and used for zip file manipulation such as adding ,extracting files, etc. 

Here I Bind the CheckboxList with the list of files from the server folder path using directory.Getfiles on pageLoad and has a download button. The checkboxList allows the user to select the files as they wish and download it. 

Default.aspx:

<form id="form1" runat="server">
        <div  style="border: 1px solid #357ae8; padding:15px 15px 15px 15px ; width: 400px; height: 250px">
            <asp:CheckBoxList ID="chkAlbum" runat="server">
            </asp:CheckBoxList>
            <asp:Button ID="btnDownload" runat="server" OnClick="btnDownload_Click" Text="Download as zip file" />
        </div>
    </form>

Code Behind Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        string[] files = Directory.GetFiles(Server.MapPath(".") + @"\Uploads");
        foreach (string file in files)
        {
           chkAlbum.Items.Add(new ListItem(Path.GetFileName(file), file));
        }
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
       Response.Clear();
       Response.ContentType = "application/zip";
       Response.AddHeader("content-disposition", "filename=" + "Donload.zip");
        using (ZipFile zip = new ZipFile())
        {
            foreach (ListItem item in chkAlbum.Items)
            {
                if (item.Selected)
                {
                   zip.AddFile(item.Value, "Album");
               }
            }
           zip.Save(Response.OutputStream);
        }
    } 

Output:

asp .net download multiple files

Post your comments / questions