Get File Listings in C#
By FoxLearn 1/16/2025 2:10:52 AM 31
Before you can start working with files, you need to include the System.IO namespace in your code.
using System.IO;
Create a DirectoryInfo Object
You will need to create an instance of the DirectoryInfo
class, which represents a directory on the file system.
For example, if you want to list files in the C:\
drive, create a DirectoryInfo
object for that directory:
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\");
Get Files Using GetFiles()
To get a list of files in the specified directory, use the GetFiles()
method, which returns an array of FileInfo
objects representing each file in the directory.
You can then loop through these FileInfo
objects and access file details like the name, size, and more.
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\"); // Get all files in the directory foreach (FileInfo file in directoryInfo.GetFiles()) { Console.WriteLine(file.Name); // Print the file name }
Filter Files by Extension
If you only want to list specific types of files (e.g., .txt
files), you can pass a search pattern (such as "*.txt"
) to the GetFiles()
method:
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\"); // Get only .txt files in the directory foreach (FileInfo file in directoryInfo.GetFiles("*.txt")) { Console.WriteLine(file.Name); // Print the file name }
Now, only .txt
files will be listed. The GetFiles()
method’s search pattern is very flexible, but there’s one caveat: you can only use one pattern at a time. If you need to list multiple types of files, you’ll have to call GetFiles()
again with a different pattern.
Handling Subdirectories
If you want to include files from subdirectories, you can use the SearchOption.AllDirectories
option with the GetFiles()
method:
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\"); // Get all files in the directory and subdirectories foreach (FileInfo file in directoryInfo.GetFiles("*", SearchOption.AllDirectories)) { Console.WriteLine(file.FullName); // Print the full file path }
Getting file listings in C# is straightforward, thanks to the DirectoryInfo
and FileInfo
classes.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#