To get the directory, C# provides a method Directory.GetDirectories. The Directory.GetDirectories method returns the names (including their paths) of subdirectories in the specified directory that match the specified search pattern, and optionally searches the subdirectories.
In the following example, * means to match zero or more characters at that position. SearchOption TopDirectoryOnly . Gets only top-level directories, SearchOption AllDirectories . Gets all top-level directories and subdirectories.
Note: The rootPath will be the root path of your system, so create a test folder and use the rootPath accordingly.
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly); foreach (string dir in dirs) { Console.WriteLine (dir); } Console.ReadLine (); }
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories); foreach (string dir in dirs) { Console.WriteLine (dir); } Console.ReadLine (); }
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory
The above is the detailed content of How to get all directories and subdirectories within a path in C#?. For more information, please follow other related articles on the PHP Chinese website!