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.
public static bool Exists (string? path);
The Exists() method returns false
if:
null
.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
and absolute paths are allowed as input. The input path is not case-sensitive. relative Relative path information is interpreted as relative to the current working directory