Keywords: C# | file search | extension | Directory.GetFiles
Abstract: This article explains how to find files with specific extensions in a folder using C#'s System.IO.Directory.GetFiles method. It provides code examples, discusses error handling, and covers advanced features like recursive search and pattern matching. Ideal for developers working with file systems.
Introduction
In programming, handling file systems is a common task, especially when needing to locate files with specific extensions. For example, finding all .txt files in a folder like C:\Random Folder. This is frequent in scenarios such as data import, log analysis, or configuration management.
Core Method
In C#, the System.IO.Directory class provides a static method GetFiles that accepts a path and a search pattern, returning an array of matching file paths. This is an efficient and straightforward approach, eliminating the need for manual directory traversal.
using System;
using System.IO;
class FileSearchExample
{
static void Main()
{
string path = @"C:\Random Folder";
string pattern = "*.txt";
try
{
string[] files = Directory.GetFiles(path, pattern);
foreach (string file in files)
{
Console.WriteLine("Found file: " + file);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
This code defines the folder path and search pattern, then calls Directory.GetFiles. A try-catch block handles potential exceptions, such as an invalid path. The returned array contains full file paths for further processing.
Advanced Usage
The GetFiles method has overloads that support search options, like recursively searching subdirectories. For instance, using SearchOption.AllDirectories parameter searches all subfolders.
string[] allTxtFiles = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
Additionally, Directory.EnumerateFiles offers lazy enumeration, suitable for large directories to reduce memory usage. Search patterns support wildcards, e.g., *.txt matches all text files, and test*.doc matches files starting with "test" and ending with ".doc".
In practice, it's advisable to validate input paths, such as using Directory.Exists to check existence, and incorporate error handling for robustness.