List all files and directories in a directory + subdirectories

derp_in_mouth picture derp_in_mouth · Sep 8, 2012 · Viewed 223.3k times · Source

I want to list every file and directory contained in a directory and subdirectories of that directory. If I chose C:\ as the directory, the program would get every name of every file and folder on the hard drive that it had access to.

A list might look like

fd\1.txt
fd\2.txt
fd\a\
fd\b\
fd\a\1.txt
fd\a\2.txt
fd\a\a\
fd\a\b\
fd\b\1.txt
fd\b\2.txt
fd\b\a
fd\b\b
fd\a\a\1.txt
fd\a\a\a\
fd\a\b\1.txt
fd\a\b\a
fd\b\a\1.txt
fd\b\a\a\
fd\b\b\1.txt
fd\b\b\a

Answer

Ruslan F. picture Ruslan F. · Sep 8, 2012
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();
 }