C# Directory Exists

Summary: in this tutorial, you’ll learn how to check if a directory exists using the Directory.Exists() static method.

Introduction to the C# Directory.Exists() method

The Directory.Exists() method returns true if a specified path to a directory exists or false otherwise:

public static bool Exists (string? path);Code language: C# (cs)

The path can be relative or absolute. If you use a relative path, the Exists() method interprets it as relative to the current working directory.

The Exists() method removes the trailing spaces from the path before checking.

Note that the path is case-sensitive on Linux file systems but case-insensitive on Windows file systems.

In practice, you use the Directory.Exists() method to check if a directory exists before carrying out other operations such as copying, moving, and deleting.

C# Directory.Exist() method example

The following program demonstrates how to use the Directory.Exists() to check if the C:\temp directory exists:

using static System.Console;

string dirname = @"C:\temp\";

if (Directory.Exists(dirname))
{
    WriteLine($"The directory {dirname} exists.");
}
else
{
    WriteLine($"The directory {dirname} does not exist.");
}Code language: C# (cs)

Output:

The directory C:\temp\ exists.Code language: C# (cs)

Summary

  • Use C# Directory.Exists() to check if a directory exists or not.
Was this tutorial helpful ?