C# Directory GetFiles() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

Definition

In C#, Directory.GetFiles() returns the full paths of files inside a folder as a string[]. Folders are not part of the result; only files.

It is one of the most used Directory methods. You can filter with a pattern such as "*.txt" and also go through every subfolder. Like all Get... methods it reads the full list first, so for huge folders prefer EnumerateFiles().

This is a static method of System.IO.Directory. Call it as Directory.GetFiles(...); there is no new Directory(). For an object that remembers one folder, see DirectoryInfo.

Syntax

Pass the folder, and optionally a pattern and a search option.

C#
string root = Path.Combine(Path.GetTempPath(), "codetofun-demo");

string[] files = Directory.GetFiles(root, "*.txt");
Array.Sort(files, StringComparer.Ordinal);

foreach (string file in files) {
    Console.WriteLine(Path.GetFileName(file));
}
CallWhat it does
GetFiles(path)All files directly inside path.
GetFiles(path, "*.txt")Only the files whose name ends in .txt.
GetFiles(path, "*.txt", SearchOption.AllDirectories)Also looks in every subfolder.

The order is not guaranteed. Sort the array before printing. If you sort full paths, items in one folder keep a stable order because they share the same start. A pattern ending in .txt can also match longer extensions on some Windows setups, so check Path.GetExtension when it matters.

Library declarations
C#
public static string[] GetFiles(string path);
public static string[] GetFiles(string path, string searchPattern);
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption);

Parameters

ParameterDescription
pathThe folder to search. It must exist.
searchPatternOptional. A file name filter such as "*.txt". Default "*".
searchOptionOptional. TopDirectoryOnly (default) or AllDirectories.

Return Value

Return ValueDescription
string[]An array of full file paths (they begin with the path you passed in). Empty, never null, when nothing matches.

C# Examples

Example 1 — Get Text Files Sorted

Create a mix of files and read only the .txt files from the top level.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-getfiles-pattern");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(Path.Combine(root, "nested"));
        File.WriteAllText(Path.Combine(root, "beta.txt"), "b");
        File.WriteAllText(Path.Combine(root, "alpha.txt"), "a");
        File.WriteAllText(Path.Combine(root, "gamma.csv"), "g");
        File.WriteAllText(Path.Combine(root, "nested", "inner.txt"), "i");

        string[] files = Directory.GetFiles(root, "*.txt");
        Array.Sort(files, StringComparer.Ordinal);

        Console.WriteLine("Found: " + files.Length);
        foreach (string file in files) {
            Console.WriteLine(Path.GetFileName(file));
        }

        Directory.Delete(root, true);
    }
}

How It Works

  1. Four files, three kinds. There are two .txt files at the top, one .csv, and another .txt inside nested.
  2. Pattern and depth. "*.txt" removes gamma.csv. Because no search option is given, inner.txt in the subfolder is also left out.
  3. Created in reverse. beta.txt was written before alpha.txt. Sorting makes the printed order alpha.txt first on every machine.

Example 2 — Find Text Files in Every Subfolder

Add SearchOption.AllDirectories and see the nested file appear.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-getfiles-deep");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(Path.Combine(root, "nested"));
        File.WriteAllText(Path.Combine(root, "alpha.txt"), "a");
        File.WriteAllText(Path.Combine(root, "beta.txt"), "b");
        File.WriteAllText(Path.Combine(root, "nested", "inner.txt"), "i");

        string[] top = Directory.GetFiles(root, "*.txt");
        string[] all = Directory.GetFiles(root, "*.txt", SearchOption.AllDirectories);
        Array.Sort(all, StringComparer.Ordinal);

        Console.WriteLine("Top: " + top.Length + ", all: " + all.Length);
        Console.WriteLine(Path.GetFileName(all[2]));
        Console.WriteLine(Path.GetFileName(Path.GetDirectoryName(all[2])));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Two calls on one tree. The first call keeps the default depth, the second asks for AllDirectories. The lengths are 2 and 3.
  2. Sorting full paths. Items in root start with the same text, and nested sorts after alpha.txt and beta.txt, so all[2] is the nested file.
  3. Reading the file name. GetFileName turns the path into inner.txt.

Example 3 — Count Files by Extension

Use the array with Path.GetExtension to tally two file types.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-getfiles-ext");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);
        string[] names = { "a.txt", "b.txt", "c.md", "d.md", "e.md" };
        foreach (string n in names) {
            File.WriteAllText(Path.Combine(root, n), "x");
        }

        string[] files = Directory.GetFiles(root);
        int txt = 0, md = 0;
        foreach (string file in files) {
            string ext = Path.GetExtension(file);
            if (ext == ".txt") txt++;
            else if (ext == ".md") md++;
        }

        Console.WriteLine("Files: " + files.Length);
        Console.WriteLine(".txt: " + txt);
        Console.WriteLine(".md: " + md);
        Console.WriteLine("Rooted: " + Path.IsPathRooted(files[0]));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Names from an array. A string array and a loop create five files, so the folder has a known size.
  2. One call, then plain code. GetFiles returns an array, so the tally loop is ordinary code that does not touch the disk again.
  3. The extension includes the dot. Path.GetExtension returns .txt and .md with the dot, so the comparison strings need the dot too.

Frequently Asked Questions

Use string[] files = Directory.GetFiles(folder). Add using System.IO; at the top of the file.
Pass a pattern as the second argument: Directory.GetFiles(folder, "*.txt").
Use Directory.GetFiles(folder, "*", SearchOption.AllDirectories).
Full paths that start with the folder you passed in. Use Path.GetFileName(path) to get only the file name.
Use EnumerateFiles for very large folders or when you may stop early, because it streams one path at a time instead of building an array first.

Next: GetFileSystemEntries()

Get files and subfolders together as one string array.

GetFileSystemEntries() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful