This code snippet helps you to understand how to get all the directories and subdirectories under a directory in C#. In the below examples shows how to get the top/root directories as well as the root directories and subdirectories under the given path or directory.
Retrieve Top Directory:
The following code will retrieve and print the top-level directories.
using System;
using System.IO;
public class FindDirectory
{
public static void Main()
{
// Root directory path
string rootPath = @"E:\Sabari\";
// Search only top/parent directory
string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly);
// Loop and print the directory name
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
Console.ReadKey();
}
}
Output:
E:\Sabari\Test Directory1
E:\Sabari\Test Directory2
Retrieve All Directories and Sub Directories:
The following code will retrieve and print the top-level directories and their subdirectories.
using System;
using System.IO;
public class FindDirectory
{
public static void Main()
{
// Root directory path
string rootPath = @"E:\Sabari\";
// Search all directories and sub directories
string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories);
// Loop and print the directory name
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
Console.ReadKey();
}
}
Output:
E:\Sabari\Test Directory1
E:\Sabari\Test Directory2
E:\Sabari\Test Directory1\Test Sub-directory1
E:\Sabari\Test Directory1\Test Sub-directory2
E:\Sabari\Test Directory1\Test Sub-directory1\Test Dir1
E:\Sabari\Test Directory1\Test Sub-directory1\Test Dir2
Comments (0)