[C#] Searching and Getting a List of Files in a Directory (Directory.GetFiles)

To get a list of file names in a specific folder, use the Directory.GetFiles method. This method allows you to filter files using “wildcards” for specific extensions or naming patterns. You can also search through subfolders by specifying search options.

目次

Table of Contents

  • Wildcard Characters and Meanings
  • Specifying SearchOption (Search Scope)
  • Implementation Sample: Searching for Log Files
  • Explanation

Wildcard Characters and Meanings

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

WildcardMeaningUsage ExampleMatching ExamplesNon-matching Examples
* (Asterisk)Zero or more characters*.txtmemo.txt, .txt, abc.txtmemo.log
? (Question mark)Exactly one characterdata_?.csvdata_1.csv, data_A.csvdata_10.csv, data.csv

Specifying SearchOption (Search Scope)

This enum specifies whether to search inside subfolders.

ValueMeaningDescription
TopDirectoryOnlyTop-level directory onlySearches only the files directly inside the specified folder (Default).
AllDirectoriesAll directoriesRecursively searches the specified folder and all its subfolders.

Implementation Sample: Searching for Log Files

The following code creates a LogData folder, places some dummy files inside, and then searches for and displays files using different patterns and options.

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // 1. Set up test environment (Create directories and dummy files)
        string rootDir = "LogData";
        string subDir = Path.Combine(rootDir, "Backup");

        // Create folders
        Directory.CreateDirectory(subDir);

        // Create files
        // Pattern 1: log_xxxx.txt directly under root
        File.WriteAllText(Path.Combine(rootDir, "log_2023.txt"), "log");
        File.WriteAllText(Path.Combine(rootDir, "log_2024.txt"), "log");
        File.WriteAllText(Path.Combine(rootDir, "error.log"), "error"); // Different extension
        
        // Pattern 2: File inside subfolder
        File.WriteAllText(Path.Combine(subDir, "log_2020.txt"), "old log");

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


        // ---------------------------------------------------------
        // Case 1: Wildcard "*" and top-level search
        // ---------------------------------------------------------
        // "*.txt" -> All files with .txt extension
        Console.WriteLine("[1] *.txt (Top directory only):");
        
        string[] txtFiles = Directory.GetFiles(rootDir, "*.txt", SearchOption.TopDirectoryOnly);
        
        foreach (var file in txtFiles)
        {
            Console.WriteLine($"  Found: {Path.GetFileName(file)}");
        }


        // ---------------------------------------------------------
        // Case 2: Wildcard "?" and recursive search
        // ---------------------------------------------------------
        // "log_????.txt" -> .txt files with exactly 4 characters after "log_"
        // SearchOption.AllDirectories -> Includes the subfolder (Backup)
        Console.WriteLine("\n[2] log_????.txt (Including subfolders):");

        string[] logFiles = Directory.GetFiles(rootDir, "log_????.txt", SearchOption.AllDirectories);

        foreach (var file in logFiles)
        {
            // Display only the file name as the path can be long
            Console.WriteLine($"  Found: {Path.GetFileName(file)}");
        }
    }
}

Execution Result

--- Target Directory: LogData ---

[1] *.txt (Top directory only):
  Found: log_2023.txt
  Found: log_2024.txt

[2] log_????.txt (Including subfolders):
  Found: log_2023.txt
  Found: log_2024.txt
  Found: log_2020.txt

Explanation

  • Return Value: Directory.GetFiles returns a string array (string[]) containing the full paths (or relative paths) of the files found.
  • Behavior of ?: As seen in Result [2], error.log is excluded because it does not match the pattern, while log_2020.txt in the subfolder is detected thanks to AllDirectories.
  • Important Note: If a folder contains tens of thousands of files, using GetFiles can be inefficient because it does not return control until the entire array is created. In such cases, consider using Directory.EnumerateFiles for better memory efficiency.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次