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".
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
Parameter
Description
path
The folder to search. It must exist.
searchPattern
Optional. A file name filter such as "*.txt". The default is "*".
searchOption
Optional. TopDirectoryOnly (default) or AllDirectories.
Return Value
Return Value
Description
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);
}
}
Output
notes.txt, todo.txt
How It Works
Four files, two folders. The tree has photo.png, two top-level text files, and one text file in nested.
Pattern cuts the list."*.txt" drops photo.png, because its name does not end in .txt.
Only the top level. With no SearchOption, deep.txt in the subfolder is not visited, which leaves two names.
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);
}
}
Output
Top level: 1
All levels: a.log b.log c.log
How It Works
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.
Default is shallow. Without a search option the call only sees a.log. Count() from LINQ walks the sequence and returns 1.
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);
}
}
Output
Files: 3
Total bytes: 35
How It Works
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.
One path at a time. The loop receives a path, builds a FileInfo, and reads its Length. Nothing is kept after the iteration ends.
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.