C# Directory.Exists

Directory, package

Directory.Exists checks if a folder exists. It is found in the System.IO namespace. As with all file handling methods, it can throw exceptions even in normal usage. For this reason care is required.


Bool keyword

The Directory.Exists method can be accessed most easily if you add using System.IO to the top of your program. The method returns a bool: true if the directory is present, and false if it is not.

Bool MethodTrue, False

Next:This program shows that on my computer C:\Users exists, but C:\Losers does not. Please forgive the bad joke.

Program that uses Directory.Exists: C#

using System;
using System.IO;

class Program
    static void Main()
	if (Directory.Exists("C:\\Users"))
	if (Directory.Exists("C:\\Losers"))




Programming tip

Often in a program you will want to create a directory if one does not exist. You can use the Directory.CreateDirectory method for this. You can see an example of this in a separate article.

Path Exists


It is sometimes important to determine if a directory or folder exists. As we saw here, the Directory.Exists method is ideal for this purpose. It can be combined with other useful methods such as Directory.CreateDirectory.


C#: File: Directory