When working with file systems in .NET, one of the most common tasks is to list directories inside a given folder. The System.IO namespace provides everything you need to achieve this in a simple and reliable way.


Listing Directories in C# Using System.IO

When working with file systems in .NET, one of the most common tasks is to list directories inside a given folder. The System.IO namespace provides everything you need to achieve this in a simple and reliable way.

Step 1: Import the Required Namespace

Start by including System.IO, which contains classes for file and directory manipulation:

using System.IO;

Step 2: Define the Target Folder

You need to specify the path of the folder you want to scan. For example:

string folderPath = @"C:\Test";

Step 3: Check if the Folder Exists

Before attempting to list directories, always validate that the folder exists to avoid runtime errors:

if (Directory.Exists(folderPath))
{
    // Proceed with listing
}
else
{
    Console.WriteLine("The specified folder does not exist.");
}

Step 4: Retrieve and Print Directories

Use Directory.GetDirectories(path) to get an array of all directories inside the folder:

string[] directories = Directory.GetDirectories(folderPath);

foreach (string dir in directories)
{
    Console.WriteLine(dir);
}

Complete Example

Here’s the full code that puts everything together:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string folderPath = @"C:\Test";

        try
        {
            if (Directory.Exists(folderPath))
            {
                Console.WriteLine($"Listing directories in: {folderPath}");

                string[] directories = Directory.GetDirectories(folderPath);

                foreach (string dir in directories)
                {
                    Console.WriteLine(dir);
                }
            }
            else
            {
                Console.WriteLine("The specified folder does not exist.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Example Output

If the folder contains three subdirectories:

C:\Test\Project1
C:\Test\Project2
C:\Test\Logs

The program will print:

Listing directories in: C:\Test
C:\Test\Project1
C:\Test\Project2
C:\Test\Logs

Technical Summary

StepTechniqueMethod
1Import libraryusing System.IO
2Validate folder existenceDirectory.Exists(path)
3List directoriesDirectory.GetDirectories(path)
4Iterate resultsforeach (string dir in directories)

✅ With just a few lines of code, you can scan directories in any folder. This is especially useful for file explorers, migration tools, or automation scripts.

Edvaldo Guimrães Filho Avatar

Published by