How to get all the directories and sub directories inside a path in C#?

CsharpServer Side ProgrammingProgramming

To get the directories C# provides a method Directory.GetDirectories. The Directory.GetDirectories method returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.

In the below example * is matches Zero or more characters in that position. SearchOption TopDirectoryOnly .Gets only the top directories and SearchOption AllDirectories .Gets all the top directories and sub directories.

Note: The rootPath will be your systems rootPath so create a testfolder and use the rootPath accoridingly.

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

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
raja
Published on 25-Nov-2020 11:51:51
Advertisements