C# Directory EnumerateFiles() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, Directory.EnumerateFiles() gives you the full paths of files in a folder, one at a time. It returns an IEnumerable<string>, and the disk is read while your foreach runs.

Folders are skipped; only files are returned. Compared with GetFiles(), it starts giving results sooner and needs less memory, which matters for folders with many thousands of files.

This is a static method of System.IO.Directory. Call it as Directory.EnumerateFiles(...); there is no new Directory(). For an object that remembers one folder, see DirectoryInfo.

Syntax

Pass the folder, and optionally a pattern like "*.txt".

C#
string root = Path.Combine(Path.GetTempPath(), "codetofun-demo");

foreach (string file in Directory.EnumerateFiles(root, "*.txt")) {
    Console.WriteLine(Path.GetFileName(file));
}
CallWhat it does
EnumerateFiles(path)Streams every file directly inside path.
EnumerateFiles(path, "*.txt")Only files whose name ends in .txt.
EnumerateFiles(path, "*.log", SearchOption.AllDirectories)Also looks inside every subfolder.

The order is not guaranteed, so sort file names before printing them. Wildcards: * means any number of characters and ? means exactly one. Pattern matching is done by the file system rules, so case rules differ between Windows and Linux.

Library declarations
C#
public static IEnumerable<string> EnumerateFiles(string path);
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern);
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption);

Parameters

ParameterDescription
pathThe folder to search. It must exist.
searchPatternOptional. A file name filter such as "*.txt". The default is "*".
searchOptionOptional. TopDirectoryOnly (default) or AllDirectories.

Return Value

Return ValueDescription
IEnumerable<string>A lazy sequence of full file paths. It is empty when nothing matches.

C# Examples

Example 1 — List Text Files in Sorted Order

Create text and picture files, then print only the sorted .txt names.

C#
using System;
using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-enumfile-pattern");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(Path.Combine(root, "nested"));
        File.WriteAllText(Path.Combine(root, "notes.txt"), "a");
        File.WriteAllText(Path.Combine(root, "todo.txt"), "b");
        File.WriteAllText(Path.Combine(root, "photo.png"), "c");
        File.WriteAllText(Path.Combine(root, "nested", "deep.txt"), "d");

        List<string> names = new List<string>();
        foreach (string file in Directory.EnumerateFiles(root, "*.txt")) {
            names.Add(Path.GetFileName(file));
        }
        names.Sort(StringComparer.Ordinal);

        Console.WriteLine(string.Join(", ", names));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Four files, two folders. The tree has photo.png, two top-level text files, and one text file in nested.
  2. Pattern cuts the list. "*.txt" drops photo.png, because its name does not end in .txt.
  3. Only the top level. With no SearchOption, deep.txt in the subfolder is not visited, which leaves two names.
  4. Sorted before printing. The names are collected and sorted with StringComparer.Ordinal, so every machine prints notes.txt first.

Example 2 — Find Log Files at Every Level

Compare a top-level search with SearchOption.AllDirectories.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-enumfile-all");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(Path.Combine(root, "logs", "old"));
        File.WriteAllText(Path.Combine(root, "a.log"), "1");
        File.WriteAllText(Path.Combine(root, "readme.md"), "2");
        File.WriteAllText(Path.Combine(root, "logs", "b.log"), "3");
        File.WriteAllText(Path.Combine(root, "logs", "old", "c.log"), "4");

        int top = Directory.EnumerateFiles(root, "*.log").Count();
        Console.WriteLine("Top level: " + top);

        List<string> all = new List<string>();
        foreach (string f in Directory.EnumerateFiles(root, "*.log", SearchOption.AllDirectories)) {
            all.Add(Path.GetFileName(f));
        }
        all.Sort(StringComparer.Ordinal);
        Console.WriteLine("All levels: " + string.Join(" ", all));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Logs at three depths. One .log file sits in root, one in logs, and one in logs\old. A readme.md is there as a decoy.
  2. Default is shallow. Without a search option the call only sees a.log. Count() from LINQ walks the sequence and returns 1.
  3. AllDirectories goes deeper. The same pattern now reaches the two logs in subfolders, so there are three results.

Example 3 — Total File Size Without Loading an Array

Visit each file once, add its length, and never store the whole list.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-enumfile-size");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);
        File.WriteAllText(Path.Combine(root, "a.txt"), "12345");
        File.WriteAllText(Path.Combine(root, "b.txt"), new string('x', 10));
        File.WriteAllText(Path.Combine(root, "c.txt"), new string('y', 20));

        long total = 0;
        int files = 0;
        foreach (string path in Directory.EnumerateFiles(root)) {
            total += new FileInfo(path).Length;
            files++;
        }

        Console.WriteLine("Files: " + files);
        Console.WriteLine("Total bytes: " + total);

        Directory.Delete(root, true);
    }
}

How It Works

  1. Known sizes. The three files hold 5, 10, and 20 plain letters. WriteAllText saves them as UTF-8 without a BOM, so each letter is one byte.
  2. One path at a time. The loop receives a path, builds a FileInfo, and reads its Length. Nothing is kept after the iteration ends.
  3. Running totals. total uses long because real folders can pass 2 GB, and files counts the visits.

Frequently Asked Questions

EnumerateFiles streams paths lazily as IEnumerable<string>. GetFiles reads every file first, then returns a string[]. Enumerate starts faster and uses less memory for large folders.
Pass a pattern: Directory.EnumerateFiles(folder, "*.txt").
Only if you pass SearchOption.AllDirectories. The default looks only at the folder itself.
Full paths. Use Path.GetFileName to get only the name.
No. Sort the names yourself when you need the same order every time.

Next: EnumerateFileSystemEntries()

Stream files and subfolders together in one lazy sequence.

EnumerateFileSystemEntries() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful