TechieClues TechieClues
Updated date Feb 22, 2021
This code snippet helps you to understand how to get all the directories and subdirectories under a directory in C#.

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

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!