Oct
19
2006
Listing files in a directory
Posted by admin under
ASP.NET 2.0
The following code snippet shows you how to list all files inside a certain folder in your web application:
foreach(string sFile in
System.IO.Directory.GetFiles( Server.MapPath("images") ))
{
string sJustFile = new System.IO.FileInfo(sFile).Name;
DoSomethingFunWithThis(sJustFile);
}
The GetFiles demands an absolute path, but since your application might be running at a webhost where you have no idea if your site is located in c:\websites\yoursite or d:\hello\whatever\yoursite etc we use the Server.MapPath to let ASP.NET create the absolute path for us.
You can also list files of just a certain type:
foreach(string sFile in
System.IO.Directory.GetFiles( Server.MapPath("images"), "*.jpg" ))
{
string sJustFile = new System.IO.FileInfo(sFile).Name;
DoSomethingFunWithThis(sJustFile);
}
Now we will only receive the jpg files available in the images folder.