How to check if a directory exists in C#

The Directory static class in the System.IO namespace provides the Exists() method to check the existence of a directory on the disk. This method takes the path of the directory as a string input, and returns true if the directory exists at the specified path; otherwise, it returns false.

Syntax

public static bool Exists (string? path);

The Exists() method returns false if:

  • The input directory does not exist.
  • The input path is null.
  • The input path is an empty string.
  • The input path is invalid.
  • The caller does not have sufficient permissions.
  • The input path is a file.

Code example

In the example below, we are using the Directory.Exists() method to check the existence of the /usercode directory, which is an existing directory in our environment.

The Directory.Exists() method returns true for this path and the program prints Directory /usercode exists.

using System;
using System.IO;
class HelloWorld
{
static void Main()
{
// Note : Directory.GetCurrentDirectory() can also return the current working directory.
string currentDirectoryPath = "/usercode";
if(Directory.Exists(currentDirectoryPath))
{
Console.WriteLine($"Directory {currentDirectoryPath} exists!");
} else
{
Console.WriteLine($"Directory {currentDirectoryPath} does not exist!");
}
}
}

Note: Both relativeRelative path information is interpreted as relative to the current working directory and absolute paths are allowed as input. The input path is not case-sensitive.