First create a DataGrid in your asp designer page. Add a Hyper link field to which files to be associated with & all other setting as bellow.
<asp:DataGrid ID="fileload" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name"
DataNavigateUrlFormatString="FetchFile.aspx?FileName={0}" DataTextField="Name"
HeaderText="File Name:" SortExpression="Name"></asp:HyperLinkColumn>
</Columns>
</asp:DataGrid>
Look above, in order fetch files from the directory another asp page fetch.aspx is refered in the DataNavigateUrlFormatString of the hyperlink column field. So create another asp page as ‘FetchFile.aspx’ & add the following code in the page load event.
string dlDir = "downloadfiles/";
string strFilename = Request.QueryString["Filename"];
string path=Server.MapPath(dlDir+strFilename);
System.IO.FileInfo toDownload = new FileInfo(path);
if (toDownload.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + toDownload.Name);
Response.AddHeader("Content-Length", toDownload.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(toDownload.FullName);
Response.End();
}
Then come into the main asp coding page where DataGrid was created earlier & write the following code into the page loade event.
string folder = Server.MapPath("downloadfiles/");
//Get the files by using directoryInfo class of system.IO assembly
DirectoryInfo di = new DirectoryInfo(folder);
FileInfo[] fri = di.GetFiles();
int countfile = fri.Count();
//Create a table & bind the file names into cells.
System.Data.DataTable table = new System.Data.DataTable();
DataColumn column;
DataRow row;
column = new DataColumn();
column.ColumnName = "Name";
column.DataType = System.Type.GetType("System.String");
table.Columns.Add(column);
for (int i = 0; i <countfile; i++)
{
row = table.NewRow();
row["Name"] = fri[i].Name.ToString();
table.Rows.Add(row);
}
//bind the table data to the data grid in designer page
fileload.DataSource = table;
fileload.DataBind();build the solution & run your main asp page. Your Data Grid will be filled with the downloadable file lists. Click any file among of them & watch your downloading.