In this post, we’ll determine whether a file exists using C#.

There are several ways to check for a file’s existence in C#. There are three possibilities while testing for a file’s existence – the file exists, the file doesn’t exist, or the file’s status is unknown if the code does not have sufficient permissions to read the specified file.

 
To check whether the specified file exists, use the File.Exists(path) method. It returns a boolean value indicating whether the file at the specified path exists or not. The File.Exists() method returns true if the file exists and false when the file doesn’t exist or the caller does not have read access to the file.

Download  Run Code

 
If you want to check the presence of a directory instead, use the Directory.Exists() method.

Download  Run Code

 
To check if a file exists in a specified directory, use the following code:

Download Code

 
The above solution iterates over all files present in the directory to check the existence of the specified file, which is not efficient. Here’s an alternative way which constructs the full path from the provided information:

Download  Run Code

 
To determine whether a path is a directory or a file, we can use the following code, which uses the FileAttributes class:

Download  Run Code

That’s all about checking if a file exists with C#.