[C#] How to Get a List of Subdirectories in a Directory (Directory.GetDirectories)

To find out what subfolders exist inside a specific folder, use the Directory.GetDirectories method. Similar to file searches, you can filter results using wildcards and choose whether to search through all levels of subfolders.

目次

Table of Contents

  • Wildcard Characters and Meanings
  • Specifying SearchOption (Search Scope)
  • Implementation Sample: Getting a List of Folders
  • Explanation and Technical Points

Wildcard Characters and Meanings

These are special characters used in the search pattern (searchPattern).

WildcardMeaningUsage ExampleMatching ExamplesNon-matching Examples
* (Asterisk)Zero or more charactersData*Data, Database, Data_BackupMyData
? (Question mark)Exactly one character202?2023, 2024, 2025202, 202301

Specifying SearchOption (Search Scope)

This specifies whether to search deeper levels, such as subfolders within subfolders.

ValueMeaningBehavior
TopDirectoryOnlyImmediate directory onlySearches only the folders directly inside the specified folder (default).
AllDirectoriesAll directoriesSearches all levels, including subfolders and their contents.

Implementation Sample: Getting a List of Folders

The following code creates a test directory structure and then finds and displays folder paths that match specific conditions.

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // 1. Set up test environment (Create directory structure)
        string rootDir = "MyDocuments";
        
        // Immediate folders
        Directory.CreateDirectory(Path.Combine(rootDir, "Photos"));
        Directory.CreateDirectory(Path.Combine(rootDir, "Music"));
        Directory.CreateDirectory(Path.Combine(rootDir, "Work_2024"));
        Directory.CreateDirectory(Path.Combine(rootDir, "Work_2025"));

        // Create a folder inside a subfolder
        Directory.CreateDirectory(Path.Combine(rootDir, "Photos", "Travel"));

        Console.WriteLine($"--- Target: {rootDir} ---\n");


        // ---------------------------------------------------------
        // Case 1: Get all folders (Top directory only)
        // ---------------------------------------------------------
        Console.WriteLine("[1] All folders (Top directory only):");

        string[] allDirs = Directory.GetDirectories(rootDir, "*", SearchOption.TopDirectoryOnly);

        foreach (var dir in allDirs)
        {
            // Use Path.GetFileName to show only the folder name instead of the full path
            Console.WriteLine($"  Folder: {Path.GetFileName(dir)}");
        }


        // ---------------------------------------------------------
        // Case 2: Get folders starting with "Work_" (Top directory only)
        // ---------------------------------------------------------
        Console.WriteLine("\n[2] Work_* (Top directory only):");

        string[] workDirs = Directory.GetDirectories(rootDir, "Work_*", SearchOption.TopDirectoryOnly);

        foreach (var dir in workDirs)
        {
            Console.WriteLine($"  Found: {Path.GetFileName(dir)}");
        }


        // ---------------------------------------------------------
        // Case 3: Search all levels (Including subfolders)
        // ---------------------------------------------------------
        Console.WriteLine("\n[3] Recursive search (AllDirectories):");

        string[] recursiveDirs = Directory.GetDirectories(rootDir, "*", SearchOption.AllDirectories);

        foreach (var dir in recursiveDirs)
        {
            // Show the full path to make the structure clear
            Console.WriteLine($"  Path: {dir}");
        }
    }
}

Execution Result

--- Target: MyDocuments ---

[1] All folders (Top directory only):
  Folder: Music
  Folder: Photos
  Folder: Work_2024
  Folder: Work_2025

[2] Work_* (Top directory only):
  Found: Work_2024
  Found: Work_2025

[3] Recursive search (AllDirectories):
  Path: MyDocuments\Music
  Path: MyDocuments\Photos
  Path: MyDocuments\Work_2024
  Path: MyDocuments\Work_2025
  Path: MyDocuments\Photos\Travel

Explanation and Technical Points

1. The Return Value is a String Array of Paths

Directory.GetDirectories returns a string[] representing the full or relative paths of the directories, not DirectoryInfo objects. If you only need the folder name, you must use Path.GetFileName(path) to extract the name from the end of the path.

2. Be Careful of Access Permission Errors

When using SearchOption.AllDirectories to search through system folders (like C:\Windows) or any folders where you do not have access rights, an UnauthorizedAccessException will occur, and the process will stop. If you need to continue searching even when an error occurs, the standard method cannot handle it. In that case, you should write a custom recursive function or use Directory.EnumerateDirectories with error handling.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次