C#
programming
directory
filenames
coding-tips

How to get only filenames within a directory using c?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, the easiest way to get filenames from a directory is to enumerate the files and strip off the directory path. The usual tools are Directory.GetFiles, Directory.EnumerateFiles, or DirectoryInfo, depending on whether you want a full array immediately or a lazy sequence.

Use Directory.GetFiles With Path.GetFileName

Directory.GetFiles returns full paths, so you normally combine it with Path.GetFileName.

csharp
1using System;
2using System.IO;
3using System.Linq;
4
5class Program
6{
7    static void Main()
8    {
9        string folder = @"C:\Temp";
10
11        string[] fileNames = Directory
12            .GetFiles(folder)
13            .Select(Path.GetFileName)
14            .ToArray();
15
16        foreach (string name in fileNames)
17        {
18            Console.WriteLine(name);
19        }
20    }
21}

This is clear and works well for small or moderate directories.

Use EnumerateFiles for Large Directories

If the directory may contain many files, prefer Directory.EnumerateFiles. It streams the results instead of materializing everything immediately.

csharp
1using System;
2using System.IO;
3
4class Program
5{
6    static void Main()
7    {
8        string folder = @"C:\Temp";
9
10        foreach (string path in Directory.EnumerateFiles(folder))
11        {
12            Console.WriteLine(Path.GetFileName(path));
13        }
14    }
15}

This is often the better default for tooling or file-processing code.

DirectoryInfo Is Also Fine

If you prefer an object-oriented style, DirectoryInfo and FileInfo expose the file name directly through the Name property.

csharp
1using System;
2using System.IO;
3
4class Program
5{
6    static void Main()
7    {
8        DirectoryInfo dir = new DirectoryInfo(@"C:\Temp");
9
10        foreach (FileInfo file in dir.GetFiles())
11        {
12            Console.WriteLine(file.Name);
13        }
14    }
15}

This is nice when you already want more metadata such as size or timestamps.

Filter by Pattern When Needed

If you only want certain files, use the search pattern argument:

csharp
1foreach (string path in Directory.EnumerateFiles(folder, "*.txt"))
2{
3    Console.WriteLine(Path.GetFileName(path));
4}

That keeps the code focused on the files you actually care about instead of filtering after enumeration.

Decide Whether You Want Extensions

Path.GetFileName returns the file name with its extension. If you want the bare name without the extension, use Path.GetFileNameWithoutExtension instead.

csharp
1foreach (string path in Directory.EnumerateFiles(folder))
2{
3    Console.WriteLine(Path.GetFileNameWithoutExtension(path));
4}

That small distinction matters in tools that later append their own extensions or display cleaner labels to users.

Handle Missing or Invalid Directories

Real code should usually validate the directory before enumerating it:

csharp
1if (!Directory.Exists(folder))
2{
3    Console.WriteLine("Folder not found");
4    return;
5}

That keeps the filename logic simple and makes failures easier to explain.

Eager Versus Lazy Enumeration

GetFiles produces the whole result set immediately, while EnumerateFiles yields values lazily. For large directories or streaming pipelines, lazy enumeration often starts faster and uses less memory.

That difference may not matter in a tiny utility, but it becomes important in backup tools, indexers, or file-processing jobs that touch large directory trees.

Wrap Enumeration if Permissions May Fail

Real-world directory traversal can fail because of permissions, locked paths, or missing drives. A small try and catch around the enumeration point makes those failures easier to diagnose without complicating the filename logic itself.

By default, these examples look only at the immediate directory. If you want recursive search, you need to ask for it explicitly:

csharp
Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)

That changes the problem significantly, so it is worth being explicit about whether subdirectories should count.

Common Pitfalls

  • 'Directory.GetFiles returns full paths, not bare file names.'
  • 'Path.GetFileName strips the directory portion but leaves the file extension in place.'
  • Use EnumerateFiles instead of GetFiles when you want lazy streaming for large directories.
  • Decide explicitly whether you want only the top directory or recursive traversal.

Summary

  • Use Directory.GetFiles(...).Select(Path.GetFileName) for a simple eager solution.
  • Use Directory.EnumerateFiles when lazy iteration is preferable.
  • Use DirectoryInfo when you want names plus richer file metadata.
  • Be explicit about whether you want only immediate files or recursive results.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.