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

王林
Release: 2023-08-23 21:05:02
forward
2751 people have browsed it

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

Output

C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
Copy after login

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

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!