How to search for files in folder in C#

By FoxLearn 11/21/2024 2:13:59 AM   14
To search for files in a folder in C#, you can use the Directory.GetFiles method from the System.IO namespace.

In C#, the System.IO namespace provides Directory and File classes to perform these operations.

How to Search for Files in Directories in C#?

The easiest way to search directories and list files in C# is by using the Directory.GetFiles() method, which retrieves an array of file paths matching a specified search pattern within a given directory.

How to use the Directory.GetFiles() method to list all the files in a directory.

For example, using Directory.GetFiles() in C#

string folderPath = @"C:\YourFolder";
string searchPattern = "*.txt"; // Search for .txt files, use "*" for all files.
// Get all files recursively
string[] files = Directory.GetFiles(folderPath, searchPattern, SearchOption.AllDirectories);
foreach (string file in files)
{
     Console.WriteLine(file);
}

In this example, we specify a directory path in a string variable and use Directory.GetFiles() to retrieve an array of file paths. A foreach loop then iterates through the array, printing each file path to the console.

An alternative to search directories and list files in C# is the Directory.EnumerateFiles() method, which returns an enumerable collection of file paths matching a specified search pattern.

How to use the Directory.EnumerateFiles() method to list all the files in a directory.

For example, using Directory.EnumerateFiles()

string folderPath = @"C:\YourFolder";
var files = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.AllDirectories).Where(file => file.EndsWith(".txt") || file.EndsWith(".log")); // Example filter
foreach (var file in files)
{
     Console.WriteLine(file);
}

In this example, we specify a directory path in a string variable and uses Directory.EnumerateFiles() to retrieve an enumerable collection of file paths. A foreach loop iterates through the collection, printing each path to the console.