How to Search for files in a directory in C#

By FoxLearn 12/25/2024 3:45:32 AM   23
In C#, managing and searching files in a directory is a common task, and Directory.EnumerateFiles() provides a powerful and efficient way to find files that meet specific criteria.

The Directory.EnumerateFiles() method is used to search for files in a specified directory. Unlike Directory.GetFiles(), which returns an array of file paths, Directory.EnumerateFiles() returns an IEnumerable<string>. This allows for more memory-efficient file processing, especially when working with directories that contain large numbers of files.

using System.IO;

string directory = @"C:\temp\";
foreach (var file in Directory.EnumerateFiles(directory, searchPattern: "*hello*"))
{
    Console.WriteLine(file);
}

The * wildcard character is used to match any sequence of characters before or after "hello," making it a flexible search pattern.

1. Searching for Files in Subdirectories

By default, Directory.EnumerateFiles() searches only the top-level directory. If you need to search through all subdirectories as well, you can specify the SearchOption.AllDirectories option.

using System.IO;

string directory = @"C:\temp\";
foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))
{
    Console.WriteLine(file);
}

This code will return file paths from all subdirectories in the specified directory.

2. Searching for Files by Extension

If you're specifically interested in files of a particular type (e.g., XML files), you can use the appropriate search pattern. For example, to find all XML files in the directory, use the following code:

using System.IO;

string directory = @"C:\temp\";
foreach (var filePath in Directory.EnumerateFiles(directory, searchPattern: "*.xml"))
{
    Console.WriteLine(filePath);
}

This search is limited to the top-level directory only. If you want to search in subdirectories, you can include SearchOption.AllDirectories.

3. Searching for the Most Recent File in a Directory

Another common scenario is finding the most recently created file in a directory. For this, you can use DirectoryInfo.EnumerateFiles(), which returns FileInfo objects instead of strings. These objects provide additional properties like CreationTimeUtc, allowing you to sort the files based on their creation time.

using System.IO;
using System.Linq;

var directoryInfo = new DirectoryInfo(@"C:\temp\");

var newestFile = directoryInfo.EnumerateFiles()
    .OrderByDescending(fileInfo => fileInfo.CreationTimeUtc)
    .First();

Console.WriteLine(newestFile.FullName);

This will output the path of the most recently created file in the directory.

Directory.EnumerateFiles() is a versatile and efficient method for searching and processing files in C#.