03 June 2009

Directory, Files Listing using GridView

Web Hosting Control Panel Type Directory Listing!!
Have you ever seen a Control Panel provided for a web hosting account? Notice the way they use, to show all the files and folders inside your sites folders? Well just in case you were wondering how to do the same using ASP.NET 2.0 then let me tell you that i have achieved the same using quiet a simple technique that i found Googling around!

The following piece of code demonstrated how by using the System.IO namespace and the ASP.NET 2.0 GridView, we can achieve the task of folder/files listing very easily........

ASPX Page:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" />


Code Behind:

protected void page_load()
{
ListFolder();
}

protected void ListFolder()
{
string basepath="~/myfolder";
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(basepath));

//For All Files
FileInfo[] fileInfo = dirInfo.GetFiles("*.*",SearchOptions.AllDirectories);

//For All Subdirectories
DirectoryInfo[] subDirInfo = dirInfo.GetDirectories("*.*",AllDirectories);

GridView1.DataSource = fileInfo;
GridView1.DataBind();

GridView2.DataSource = subDirInfo;
GridView2.DataBind();
}

As you can see this method takes very little code and you can even customize it to provide delete functionality. Furthermore by combining the files and folders dataset we can achieve a complete directory listing.

1 comment:

web hosting said...

Choosing a good web hosting provider is so important for your online business that you have to make your decision seriously.

Thanks for sharing.