
How can you determine if a folder or directory exists on the computer in your C# program? With the Directory.Exists method you can determine this in a clear way.
This C# article looks at the Directory.Exists method in System.IO.
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; false if it is not. This program shows that on my computer C:\Users exists, but C:\Losers does not.
Program that uses Directory.Exists [C#]
using System;
using System.IO;
class Program
{
static void Main()
{
if (Directory.Exists("C:\\Users"))
{
Console.WriteLine("Users");
}
if (Directory.Exists("C:\\Losers"))
{
Console.WriteLine("Losers");
}
}
}
Output
Users
Often in a program you will want to create a directory if one does not exists. You can use the Directory.CreateDirectory method for this. You can see an example of this in a separate article.
Path ExistsIt 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 to implement useful behavior.
Directory.CreateDirectory File Handling