Sabari M Sabari M
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

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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