C# Directory.GetFiles, Get File List

Directory.GetFiles returns the file names in a folder. It is found in the System.IO namespace. It returns a string array—this contains the full paths of all the files contained inside the specified directory.

String Array

Example. You must include the System.IO namespace with a using directive at the top of your file, or use the fully qualified name System.IO.Directory.GetFiles type. The example program here uses the C:\ directory.

Also: It filters the files in that directory and only displays the ones with the "BIN" extension.

C# program that gets files in directories

using System;
using System.IO;

class Program
    static void Main()
	// Put all file names in root directory into array.
	string[] array1 = Directory.GetFiles(@"C:\");

	// Put all txt files in root directory into array.
	string[] array2 = Directory.GetFiles(@"C:\", "*.BIN"); // <-- Case-insensitive

	// Display all files.
	Console.WriteLine("--- Files: ---");
	foreach (string name in array1)

	// Display all BIN files.
	Console.WriteLine("--- BIN Files: ---");
	foreach (string name in array2)


--- Files: ---
    (All files in your C:\ folder)
--- BIN Files: ---
    (All .bin, .BIN files in your C:\ folder)

This method is static. You do not need to create a Directory instance to use it. The first parameter to the method is the directory path. In a Windows Forms program, you can use Environment.SpecialFolder and FolderBrowerDialog.


Note: In ASP.NET, you can use Server.MapPath or the Request.PhysicalApplicationPath property.


Next, the second parameter uses the pattern "*.BIN". You have seen these patterns in the "Open File" dialogs in Windows before. The pattern string is case-insensitive, meaning it will match files ending in "BIN", "Bin" and "bin".

Discussion. You can get a List collection of the file paths in a directory. To get the List, you will use the same method calls as in the code example. However, you can convert the arrays to Lists with the ToList extension method.

Tip: Include the System.Linq namespace at the top first—it is included by default in new files.

ToListConvert List to ArrayList

Recursively scan folders. Often you will need to get the list of files in a certain directory, and then scan all subdirectories in the folder. There are several ways to accomplish this task, including using true recursion.

Recursive File List

Performance. Directory.GetFiles is fast when used on small directories with few files. But for large directories, with thousands of files, Directory.EnumerateFiles is faster. A benchmark of these methods is available.

EnumerateFiles, GetFiles Benchmark

Summary. We saw the Directory.GetFiles method, which will return the list of files in a specified directory on your hard drive, using the C# language. We tested the method on the C:\ root directory, and discussed issues related to its usage.