Summary: in this tutorial, you’ll learn how to check if a directory exists using the
static method.Directory.Exists
()
Introduction to the C# Directory.Exists() method
The
method returns Directory.Exists
()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
method to check if a directory exists before carrying out other operations such as copying, moving, and deleting.Directory.Exists
()
C# Directory.Exist() method example
The following program demonstrates how to use the
to check if the C:\temp directory exists: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#
to check if a directory exists or not.Directory.Exists
()