List all files and directories in a directory + subdirectories
string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);
where *.*
is pattern to match files
If the Directory is also needed you can go like this:
foreach (var file in allfiles){
FileInfo info = new FileInfo(file);
// Do something with the Folder or just add them to a list via nameoflist.add();
}
Directory.GetFileSystemEntries
exists in .NET 4.0+ and returns both files and directories. Call it like so:
string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);
Note that it won't cope with attempts to list the contents of subdirectories that you don't have access to (UnauthorizedAccessException), but it may be sufficient for your needs.
public static void DirectorySearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
{
Console.WriteLine(Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(Path.GetFileName(d));
DirectorySearch(d);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Note: the function shows only names without relative paths.