We do have a folder (and a number of sub folders) with a number of various files in those folders (and sub folders). Now we do need to list all those files in an asp.net gridview control [for the purpose of organizing those files, or for the preview of files uploaded till now, say]. We can do it in asp.net using the System.IO namespace. In this article, I am going to show the coding for displaying all files in a folder in an asp.net gridview. In fact, as a bonus, we will do the listing of all files in a root folder and all its subfolders also.
Fig: Snapshot of displaying all files in a folder and its subfolders in an asp.net gridview control
Design Page Markup (ListFiles.aspx)
We first need to have a web page with the gridview control in it.
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
Remember, we have set the AutoGenerateColumns field to true. So all the fields that is present in our source will be displayed by the gridview, each as a separate column. (I have removed the formatting of the gridview markup to make the code clear. Please your own formatting for the gridview.)
Code behind page (ListFiles.aspx.cs)
Now here goes the actual code to bind all the files in the folder "Resources", that resides at the root of the web site, and all its subfolders.
protected void Page_Load(object sender, EventArgs e)
public void GetFilesAndFolders()
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Resources"));
FileInfo fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
GridView1.DataSource = fileInfo;
We have used the DirectoryInfo and FileInfo classes of the System.IO namespaces. The DirectoryInfo class will get the root directory of the provided folder name. And we have used the DirectoryInfo class's GetFiles method. This method has two overloads. We can specify the file patterns (e.g. "*.txt" for text files only, or "*.*" for all types of files etc) and the search option- if to list all the files in all the subdirectories of the root directory (in our case, "Resources" folder) provided as the input, or just to list the files in the root directory.
When we browse the page, we see the gridview populated with 13 fields, which I hope need no explanation. However for your reference I have listed the fields here: LastAccessTimeUtc, Length, LastWriteTime, LastWriteTimeUtc, FullName, IsReadOnly, CreationTimeUtc, LastAccessTime, CreationTime, Name, Exists, Extention, and DirectoryName. For the description of each field, please visit FileInfo class Properties, msdn document.
Now from those thirteen fields, we can choose and display the required ones. Please don't forget to share your views, suggestions or comments as always. Thank you. Happy programming!