Use Directory.GetDirectories to get subdirectories of the directory specified by "your_directory_path". The result is an array of strings.
var directories = Directory.GetDirectories("your_directory_path");
By default, this returns only subdirectories one level. There are options for returning all recursively and for filtering the results described here , and shown in Clive's answer.
UnauthorizedAccessException Prevention
Itβs easy that you get an UnauthorizedAccessException if you end up in a directory that you donβt have access to.
You may need to create your own method that handles the exception, for example:
public class CustomSearcher { public static List<string> GetDirectories(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) { if (searchOption == SearchOption.TopDirectoryOnly) return Directory.GetDirectories(path, searchPattern).ToList(); var directories = new List<string>(GetDirectories(path, searchPattern)); for (var i = 0; i < directories.Count; i++) directories.AddRange(GetDirectories(directories[i], searchPattern)); return directories; } private static List<string> GetDirectories(string path, string searchPattern) { try { return Directory.GetDirectories(path, searchPattern).ToList(); } catch (UnauthorizedAccessException) { return new List<string>(); } } }
And then name it like this:
var directories = CustomSearcher.GetDirectories("your_directory_path");
Grant Winney 04 Sep 2018-11-11T00: 00Z
source share