Introduction:
In this article I explain how to bind files in gridview and
how to download selected files in zip format.
Requirement:
2.
Following name space
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using Ionic.Zip;
add Ionic.Zip.dll in to your bin
folder in application then add above
name spaces .
Code .aspx :
I have some files in my
application ->files ->file1.txt and file2.doc I bind these file sin
gridview .But before binding of gridview I design my page.Write belos code to
know what I have done :
<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>
Here you can see I have taken a gridview with checkbox and a button
with the text delete.
Code.cs :
Bind files in Gridview:
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, when you
save all these and view the page in browser you ll see all files in gridview .
Now write the
below code on the Button delete 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();
}
When you write this code you have
done with the code to download selected files in zipformat.Just save all again
and view the page in browser it ll work fine.
Thanks
No comments:
Post a Comment