Summary: in this tutorial, you’ll learn how to list files that match a specified search pattern using the Directory.EnumerateFiles() method.
Introduction to the C# Directory.EnumerateFiles() method
The method returns an enumerable collection (Directory.EnumerateFiles()IEnumerable<string>) of file names that match a specified search pattern.
The following shows the syntax of the method:Directory.EnumerateFiles()
public static IEnumerable<string> EnumerateFiles(
string path,
string searchPattern,
SearchOption searchOption
);Code language: C# (cs)In this syntax:
- The
pathspecifies a relative path or an absolute path to a directory for listing the files. - The
searchPatternspecifies a search pattern to match against the filenames. - The
searchOptioninstructs the method to search only the current directory (SearchOption.TopDirectoryOnly) or include all subdirectories (SearchOptioin.AllDirectories).
The searchPattern can contain wildcards like * and ?:
- Asterisk (
*) – matches zero or more characters. - Question mark (
?) – matches exactly one character.
The searchPattern doesn’t support regular expressions.
C# listing files example
The following program demonstrates how to use the Directory.EnumerateFiles() method to list all the text files in the C:\backup directory:
using static System.Console;
string path = @"C:\backup";
var filenames = Directory.EnumerateFiles(
path,
"*.txt",
SearchOption.AllDirectories
);
foreach (var filename in filenames)
{
WriteLine(filename);
}Code language: C# (cs)How it works.
First, define a variable named path that stores the path to the directory to search:
string path = @"C:\backup";Code language: JavaScript (javascript)Second, search for the text file in the C:\backup directory and all of its subdirectories. The pattern *.txt matches the file names that have the .txt extension. And the SearchOption.AllDirectories searches for text files in all subdirectories of the C:\backup directory:
var filenames = Directory.EnumerateFiles(
path,
"*.txt",
SearchOption.AllDirectories
);Code language: JavaScript (javascript)Third, iterate through the filenames and write them to the console:
foreach (var filename in filenames)
{
WriteLine(filename);
}Code language: PHP (php)Summary
- Use C#
method to return anDirectory.EnumerateFiles()IEnumerable<string>of filenames that match specified criteria.