Thursday, 22 May 2014

Bind Files in Gridview and Download in ZIP Folder in ASP.NET

Introduction

This article shows how to bind files in a GridView and how to download selected files in zip format.


Requirements 
Dll Ionic.Zip.dll 

ASPX Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<
head>    <title>Download in zip format</title>
</
head>
<
body>    <form id="form1" runat="server">        <div>            <br />            <asp:Label ID="lbl_txt" runat="server" Font-Bold="true" ForeColor="Red" />        </div>        <asp:GridView ID="gridview1" CellPadding="5" runat="server" AutoGenerateColumns="false">            <Columns>                <asp:TemplateField>                    <ItemTemplate>                        <asp:CheckBox ID="chk_Select" runat="server" />                    </ItemTemplate>                </asp:TemplateField>                <asp:BoundField DataField="Text" HeaderText="FileName" />            </Columns>            <HeaderStyle BackColor="white" Font-Bold="true" ForeColor="White" />        </asp:GridView>        <asp:Button ID="btn_Download" Text="Download " runat="server" OnClick="btnDownload_Click" />    </form>
</
body>
</
html>



CS Page:

protected void BindGridview()
{
    
string[] files_Path = Directory.GetFiles(Server.MapPath("~/files/"));
    List<ListItem> files =
new List<ListItem>();
   
foreach (string path in files_Path)
    {
        files.Add(
new ListItem(Path.GetFileName(path)));
    }
        gridview1.DataSource = files;
        gridview1.DataBind();
    }
    Call
this function on pageload :
   
if (!IsPostBack)
    {
        BindGridview();
    }
}



Now write the following code for the Download button click:
using (ZipFile zip = new ZipFile())
{
   
foreach (GridViewRow gr in gridview1.Rows)
    {
    CheckBox chk = (CheckBox)gr.FindControl(
"chkSelect");
   
if (chk.Checked)
    {
       
string fileName = gr.Cells[1].Text;
       
string filePath = Server.MapPath("~/files/" + fileName);
        zip.AddFile(filePath,
"files");
    }
}
Response.Clear();
Response.AddHeader(
"Content-Disposition", "attachment; filename=DownloadedFile.zip");Response.ContentType = "application/zip";zip.Save(Response.OutputStream);Response.End();}
 

No comments:

Post a Comment