I’m working on a project and I need to list all subdirectories in a directory. For example, how could I list all the subdirectories in drive C:?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
Directory.GetDirectoriesto get the subdirectories of the directory specified by “your_directory_path”. The result is an array of strings.By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive’s answer.
Avoiding an UnauthorizedAccessException
It’s easily possible that you’ll get an
UnauthorizedAccessExceptionif you hit a directory to which you don’t have access.You may have to create your own method that handles the exception, like this:
And then call it like this:
This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would’ve thrown an
UnauthorizedAccessException, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.