Sunday, May 10, 2009

List all the files in a directory on a web form in asp.net

Question :
List all the files in a directory on a web form. The files must be displayed in a gridview control. The name of the file and create date must be displayed.

Answer:
1.
Create a new web form. Drag and drop a gridview control from the toolbox onto the webform.

2. Create 2 bound fields for the gridview. One bound field will display the file name and the other will display the create date.

3. The HTML for your web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListFiles.aspx.cs" Inherits="ListFiles" %>


List all the files in a directory













4. In the code behind file write a function which can get the list of files from the directory and bind to the gridview. The function is as shown below.
private void LoadFiles()
{
/* Create an instance of DirectoryInfo class for enumarating through the directory. */
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("FilesDirectory"));
/* Call the GetFiles() instance method of the DirectoryInfo class object, which will return a files list from the current directory */
System.IO.FileInfo[] fiFiles = dirInfo.GetFiles();
/* Create a DataTable which can be used as the datasource for the gridview */
DataTable dtFileList = new DataTable("Files");
/* Create a DataColumn for file name */
DataColumn dcFileName = new DataColumn("FileName");
/* Create a DataColumn for file create date */
DataColumn dcDateCreated = new DataColumn("DateCreated", typeof(DateTime));
/* Add the 2 data columns to the data table */
dtFileList.Columns.Add(dcFileName);
dtFileList.Columns.Add(dcDateCreated);
/* Now loop through each FileInfo object and get the file name and file create date */
foreach (System.IO.FileInfo f in fiFiles)
{
DataRow dtNewRow = dtFileList.NewRow();
/* Get the file name using FileInfo object "Name" property */
dtNewRow["FileName"] = f.Name.ToString();
/* Get the file create date and time using FileInfo object "CreationTime" property */
dtNewRow["DateCreated"] = f.CreationTime.ToShortDateString();
/* Add the row to the DataTable */
dtFileList.Rows.Add(dtNewRow);
}
/* Set the datatable as the DataSource for the gridview and call the DataBind() method */
GridView1.DataSource = dtFileList;
GridView1.DataBind();
}

5. Finally call the LoadFiles() method on the page load event handler as shown below.
protected void Page_Load(object sender, EventArgs e)
{
LoadFiles();
}

Testing the application:
1.
Right click on the project name in solution explorer, and left click on "NewFolder"
2. Rename the "NewFolder" to "FilesDirectory"
3. Drag and Drop some files into the directoy.
4. Then run the application. All the files in the "FilesDirectory" folder will be shown in the gridview.


No comments:

Post a Comment