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 the 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
where
*.*
is pattern to match filesIf the Directory is also needed you can go like this:
If you don't have access to a subfolder inside the directory tree, Directory.GetFiles stops and throws the exception resulting in a null value in the receiving string[].
Here, see this answer https://stackoverflow.com/a/38959208/6310707
It manages the exception inside the loop and keep on working untill the entire folder is traversed.
The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.
Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.
Use the
GetDirectories
andGetFiles
methods to get the folders and files.Use the
SearchOption
AllDirectories
to get the folders and files in the subfolders also.