Home  >  Article  >  Backend Development  >  How to get all directories and subdirectories within a path in C#?

How to get all directories and subdirectories within a path in C#?

王林
王林forward
2023-08-23 21:05:022770browse

How to get all directories and subdirectories within a path in C#?

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.

Example 1

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 ();
}

Output

C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2

The Chinese translation of Example 2

is:

Example 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 ();
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete