0
0
CsharpHow-ToBeginner · 3 min read

How to List Files in Directory in C# Quickly and Easily

In C#, you can list files in a directory using System.IO.Directory.GetFiles(). This method returns an array of file paths from the specified directory, which you can loop through to access each file name.
📐

Syntax

The basic syntax to list files in a directory is:

  • Directory.GetFiles(path): Returns all file paths in the directory.
  • path: The string path to the directory you want to list files from.

You can also use an optional search pattern like "*.txt" to filter files by extension.

csharp
string[] files = Directory.GetFiles("C:\\MyFolder");
💻

Example

This example shows how to list all files in the C:\ExampleFolder directory and print their names to the console.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "C:\\ExampleFolder";
        string[] files = Directory.GetFiles(path);

        foreach (string file in files)
        {
            Console.WriteLine(Path.GetFileName(file));
        }
    }
}
Output
file1.txt image.png document.pdf
⚠️

Common Pitfalls

Common mistakes when listing files include:

  • Using an incorrect or non-existent directory path, which throws DirectoryNotFoundException.
  • Not handling exceptions for permissions or access issues.
  • Forgetting to escape backslashes in the path string (use \\ or verbatim strings @"C:\ExampleFolder").

Always check if the directory exists before listing files to avoid errors.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "C:\\WrongPath";

        if (Directory.Exists(path))
        {
            string[] files = Directory.GetFiles(path);
            foreach (string file in files)
            {
                Console.WriteLine(Path.GetFileName(file));
            }
        }
        else
        {
            Console.WriteLine("Directory does not exist.");
        }
    }
}
Output
Directory does not exist.
📊

Quick Reference

MethodDescription
Directory.GetFiles(path)Returns all file paths in the directory.
Directory.GetFiles(path, "*.txt")Returns all .txt files in the directory.
Path.GetFileName(filePath)Extracts the file name from a full file path.
Directory.Exists(path)Checks if the directory exists before accessing it.

Key Takeaways

Use Directory.GetFiles() to get all file paths in a directory.
Always check if the directory exists with Directory.Exists() to avoid errors.
Escape backslashes in paths or use verbatim strings to write paths correctly.
Use Path.GetFileName() to get just the file name from a full path.
Handle exceptions for permissions and invalid paths to make your code robust.