Reading file names, respectively?
Categories:
Efficiently Reading File Names in C#

Learn various C# methods to list and filter file names within directories, including recursive options and performance considerations.
Reading file names from a directory is a common task in many C# applications, whether you're building a file management tool, processing data, or simply listing available resources. C# provides several robust ways to achieve this, each with its own advantages depending on the specific requirements of your application, such as performance, error handling, and the need for recursive searches.
Basic File Name Retrieval with Directory.GetFiles
The System.IO.Directory.GetFiles
method is the most straightforward way to retrieve an array of file paths (including file names) from a specified directory. It offers overloads to filter files by a search pattern and to specify search options, such as whether to include subdirectories.
using System.IO;
public class FileLister
{
public static void ListFilesInDirectory(string path)
{
try
{
// Get all files in the specified directory
string[] files = Directory.GetFiles(path);
Console.WriteLine($"Files in '{path}':");
foreach (string file in files)
{
Console.WriteLine($"- {Path.GetFileName(file)}");
}
// Get all .txt files in the specified directory
string[] txtFiles = Directory.GetFiles(path, "*.txt");
Console.WriteLine($"\nText files in '{path}':");
foreach (string file in txtFiles)
{
Console.WriteLine($"- {Path.GetFileName(file)}");
}
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"Error: Directory not found at '{path}'.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Error: Access to '{path}' is denied.");
}
}
}
Using Directory.GetFiles
to list files and filter by extension.
try-catch
blocks) when working with file system operations to gracefully manage scenarios like non-existent directories or permission issues.Recursive File Listing with SearchOption
To include files in subdirectories, you can use the SearchOption.AllDirectories
enumeration with Directory.GetFiles
. This will traverse the entire directory tree rooted at the specified path. For very large directory structures, this can be memory-intensive as it loads all file paths into an array at once.
using System.IO;
public class RecursiveFileLister
{
public static void ListAllFilesInDirectory(string path)
{
try
{
// Get all files, including those in subdirectories
string[] allFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
Console.WriteLine($"All files (including subdirectories) in '{path}':");
foreach (string file in allFiles)
{
Console.WriteLine($"- {Path.GetFileName(file)}");
}
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"Error: Directory not found at '{path}'.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Error: Access to '{path}' is denied.");
}
}
}
Listing files recursively using SearchOption.AllDirectories
.
flowchart TD A[Start: Specify Directory Path] --> B{Call Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)} B --> C{Does Directory Exist?} C -- No --> D[Handle DirectoryNotFoundException] C -- Yes --> E{Are Permissions Granted?} E -- No --> F[Handle UnauthorizedAccessException] E -- Yes --> G[Retrieve All File Paths (including subdirectories)] G --> H{Iterate through File Paths} H --> I[Extract File Name (Path.GetFileName)] I --> J[Display File Name] J --> H H -- End of Files --> K[End]
Flowchart for recursive file listing using Directory.GetFiles
.
Memory-Efficient Listing with Directory.EnumerateFiles
For scenarios involving very large directories or when you only need to process files one by one (e.g., streaming data), Directory.EnumerateFiles
is a more memory-efficient alternative. It returns an IEnumerable<string>
, which means it yields file paths as they are discovered, rather than loading all of them into memory at once. This is particularly useful for preventing OutOfMemoryException
errors.
using System.IO;
using System.Linq;
public class EnumerateFileLister
{
public static void EnumerateFilesInDirectory(string path)
{
try
{
// Enumerate all .log files, including subdirectories
var logFiles = Directory.EnumerateFiles(path, "*.log", SearchOption.AllDirectories);
Console.WriteLine($"Enumerating log files (including subdirectories) in '{path}':");
foreach (string file in logFiles)
{
Console.WriteLine($"- {Path.GetFileName(file)}");
}
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"Error: Directory not found at '{path}'.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Error: Access to '{path}' is denied.");
}
}
}
Using Directory.EnumerateFiles
for memory-efficient file listing.
Directory.EnumerateFiles
is more memory-efficient, it still performs I/O operations for each file. For extremely performance-critical applications, consider asynchronous I/O or parallel processing if applicable.Extracting Just the File Name
Both Directory.GetFiles
and Directory.EnumerateFiles
return full paths to the files. To get just the file name (e.g., document.txt
instead of C:\Folder\document.txt
), you should use Path.GetFileName()
or Path.GetFileNameWithoutExtension()
from the System.IO.Path
class.
using System.IO;
public class FileNameExtractor
{
public static void ExtractNames(string fullPath)
{
string fileName = Path.GetFileName(fullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
string fileExtension = Path.GetExtension(fullPath);
Console.WriteLine($"Full Path: {fullPath}");
Console.WriteLine($"File Name: {fileName}");
Console.WriteLine($"File Name (without extension): {fileNameWithoutExtension}");
Console.WriteLine($"File Extension: {fileExtension}");
}
public static void Main(string[] args)
{
ExtractNames("C:\\Users\\Public\\Documents\\report.pdf");
ExtractNames("\\Server\\Share\\image.jpg");
ExtractNames("file_without_extension");
}
}
Demonstrating Path.GetFileName
and Path.GetFileNameWithoutExtension
.