C# List Files

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 Directory.EnumerateFiles() method returns an enumerable collection (IEnumerable<string>) of file names that match a specified search pattern.

The following shows the syntax of the Directory.EnumerateFiles() method:

public static IEnumerable<string> EnumerateFiles(
    string path, 
    string searchPattern, 
    SearchOption searchOption
);Code language: C# (cs)

In this syntax:

  • The path specifies a relative path or an absolute path to a directory for listing the files.
  • The searchPattern specifies a search pattern to match against the filenames.
  • The searchOption instructs 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# Directory.EnumerateFiles() method to return an IEnumerable<string> of filenames that match specified criteria.
Was this tutorial helpful ?