Listing Files In Directories with C#
One of the coolest things about the ASP.NET is that it comes with a very rich set of objects to play with. The following is an example of how easy it is to accomplish the tast of listing files in a given directory on your web server. The snippet of code simply accesses a directory and pulls all the files into a collection that we then iterate through. Take a further look into the DirectoryInfo and FileInfo class for some other usefull methods.
The following live sample that will list all files in the Demos folder on the server. Note only files with the extension .aspx will be listed, the source code is also below.
void Page_Load(object s, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.aspx");
foreach(FileInfo fi in rgFiles)
{
Response.Write("<br><a href=" + fi.Name + ">" + fi.Name + "</a>");
}
}
Have fun!