Get File Listings in C#

By FoxLearn 1/16/2025 2:10:52 AM   31
To get file listings in C#, you can use the System.IO namespace, which provides classes like DirectoryInfo and FileInfo for interacting with the file system.

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.