Directory.GetFiles in C#: How to Retrieve Only Filenames Without Full Paths

Nov 23, 2025 · Programming · 8 views · 7.8

Keywords: C# | File Operations | Path Handling

Abstract: This article provides an in-depth analysis of retrieving only filenames without full paths when using the Directory.GetFiles method in C#. It explores the core principles of the Path.GetFileName method, presents comprehensive code examples, and compares performance with alternative approaches. The discussion includes the FileInfo class as an option and guides developers in selecting optimal file handling strategies.

Problem Context and Core Requirements

In C# file system operations, the Directory.GetFiles method is commonly used to retrieve all files in a specified directory. However, by default, it returns an array of filenames that include the full path, such as ["C:\dir\file1.txt", "C:\dir\file2.txt"]. In practical development, programmers often need only the filenames themselves, like ["file1.txt", "file2.txt"], to avoid the interference of path prefixes.

Core Solution: The Path.GetFileName Method

System.IO.Path.GetFileName is the standard method for addressing this issue. It takes a file path string as input and returns the filename portion of the path. Its internal implementation is based on parsing path separators, ensuring correct handling of path formats across different operating systems.

Here is a complete implementation example:

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

In this code:

In-Depth Analysis of Method Principles

The working principle of Path.GetFileName is based on string processing algorithms:

  1. Identify the last directory separator in the path string (\ for Windows, / for Unix systems)
  2. Extract all characters after the separator as the filename
  3. If no separator is present, return the original string

This design ensures cross-platform compatibility while maintaining high execution efficiency.

Analysis and Comparison of Alternative Approaches

Although the FileInfo class can be used for similar functionality:

FileInfo[] fileInfos = new DirectoryInfo(dir).GetFiles();
foreach(FileInfo fileInfo in fileInfos)
    Console.WriteLine(fileInfo.Name);

This method incurs significant performance overhead:

Best Practices Recommendations

Considering performance and maintainability:

  1. Prioritize the combination of Path.GetFileName and Directory.GetFiles
  2. Consider the FileInfo approach only when file metadata is required
  3. Handle potential exceptions, such as non-existent directories or insufficient access permissions

By adopting this optimized solution, developers can achieve full functionality while ensuring optimal performance.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.