C# Reference ยท Files and I/O
Directory.EnumerateFiles() and friends
Reference for Directory.EnumerateFiles, EnumerateDirectories and EnumerationOptions in C#: patterns, recursion, lazy enumeration and skipping inaccessible folders.
Directory.EnumerateFiles() walks a folder and yields file paths one at a time. Its siblings EnumerateDirectories() and EnumerateFileSystemEntries() do the same for subfolders or for both. Because the result is a lazy IEnumerable<string>, you can start processing the first entries immediately and stop early, which matters for large trees. The older GetFiles() family collects everything into an array before returning.
You can filter by a simple wildcard pattern and choose whether to descend into subfolders. For finer control, pass an EnumerationOptions object: it can skip folders you cannot read, control case matching, limit the recursion depth and skip hidden or system entries.
foreach (string path in Directory.EnumerateFiles(root, "*.log", SearchOption.AllDirectories)) { Console.WriteLine(path); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static IEnumerable<string> Directory.EnumerateFiles(string path); public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern); public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern, SearchOption searchOption); public static IEnumerable<string> Directory.EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions); // Same overloads: EnumerateDirectories, EnumerateFileSystemEntries
| Name | Description |
|---|---|
path |
The folder to read. Relative paths are resolved against the current working directory. |
searchPattern |
A wildcard pattern for the entry name: * matches any run of characters, ? matches exactly one. Default "*". It is not a regular expression and it matches names only, never the directory part. |
searchOption |
TopDirectoryOnly (default) or AllDirectories. |
enumerationOptions |
An EnumerationOptions object with RecurseSubdirectories, MaxRecursionDepth, IgnoreInaccessible (default true), MatchCasing, MatchType, AttributesToSkip, ReturnSpecialDirectories and BufferSize. |
Returns: a lazy IEnumerable<string> of paths. Each path is the path argument combined with the entry's relative location, so a relative input gives relative results.
Errors: DirectoryNotFoundException if the folder does not exist, ArgumentException for an invalid pattern, UnauthorizedAccessException for an unreadable root. PathTooLongException and IOException are possible during the walk.
Usage notes
- Lazy vs. eager.
Enumerate*yields entries as the disk is read;GetFiles(),GetDirectories()andGetFileSystemEntries()return a complete array. UseEnumerate*for big trees or when you stop early withFirst()orTake(), andGet*when you need the count or want to iterate twice. - Order is not guaranteed. The order depends on the file system. Call
.Order()(orOrderBy) when you need stable output, as the examples do. - The tree can change under you. Files created or deleted while you iterate may or may not appear. Do not delete the folder you are walking from inside the loop.
- Inaccessible folders are skipped. A new
EnumerationOptionshasIgnoreInaccessible = true, so folders you cannot read are silently left out of a recursive walk. Set it tofalseif you want the exception instead. - Matching rules. With the default
MatchType.Simple,*and?work the same on every platform. Case sensitivity follows the platform by default (insensitive on Windows, sensitive on Linux);MatchCasingoverrides that. - Hidden and system entries. By default
AttributesToSkipisHidden | System, so such entries are left out; set it to0to include them. - Rich metadata. For sizes and timestamps of many files,
new DirectoryInfo(path).EnumerateFiles()returnsFileInfoobjects, andFileSystemEnumerable<T>gives you a zero-allocation transform on the raw entry data. - Filtering with LINQ. For anything beyond a wildcard (size, extension lists, name rules), enumerate with
"*"and filter in aWhere.