Iterate through a root directory and get all files in it?
hi i am creating a application and i want to know the each and every file which is present under that one folder .i.e. how can i iterate through a root directory and get the each files visit at li开发者_运维百科st once.
If you just need to list them all at once, you can just use the overload for GetFiles that includes the option.
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.*", SearchOption.AllDirectories);
Obviously, in a web app you wouldn't likely have access to "c:\MyDir", so you can replace that with a variable holding the results of a MapPath call like so:
var rootDir = Server.MapPath("~/App_Data");
Use the Directory.EnumerateFiles(String, String, SearchOption) function with SearchOption.AllDirectories
:
foreach (var file in Directory.EnumerateFiles(@"c:\", "*.txt", SearchOption.AllDirectories))
{
// Do stuff here
}
EnumerateFiles method is way faster than GetFiles method since it actually just returns the enumerator and does not actually access the files until they are red.
You can use the DirectoryInfo and FileInfo classes as well as a recursive function.
void Main()
{
DirectoryInfo info = new DirectoryInfo(@"C:\Personal");
ListContents(info);
}
public void ListContents(DirectoryInfo info)
{
foreach(var dir in info.GetDirectories())
{
ListContents(dir);
}
foreach(var file in info.GetFiles())
{
Console.WriteLine(file.FullName);
}
}
精彩评论