C# File.Exists Method

File image with lines of text

You want to see if a specific file exists on the computer's hard drive using the C# programming language. There are several ways of doing this. File.Exists is the easiest and most terse way of checking that the file exists.

Example

First, the usage of File.Exists is very straightforward and should be easy to add to your program. To get its fully qualified name, it is easiest to include the System.IO namespace with a using directive at the top. To understand the next example, you have to imagine that the files tested actually exist or don't exist on the hard disk.

Program that uses File Exists [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// See if this file exists in the SAME DIRECTORY.
	if (File.Exists("TextFile1.txt"))
	{
	    Console.WriteLine("The file exists.");
	}
	// See if this file exists in the C:\ directory. [Note the @]
	if (File.Exists(@"C:\tidy.exe"))
	{
	    Console.WriteLine("The file exists.");
	}
	// See if this file exists in the C:\ directory [Note the '\\' part]
	bool exists = File.Exists("C:\\lost.txt");
	Console.WriteLine(exists);
    }
}

Output

The file exists.
The file exists.
False

File.Exists method result. The File.Exists method returns a Boolean value, which means you can either test it directly in an if conditional statement or assign its result to a bool. Usually, you will just use it in an if.

Implementation

.NET Framework information

The file existence method is well-known in many languages, but it is implemented differently in all of them. The following code shows how the File.Exists method is implemented on the .NET Framework, which includes C# and VB.NET. It eventually calls into the InternalExists method.

Part of File.Exists method [C#]

path = Path.GetFullPathInternal(path);
new FileIOPermission(FileIOPermissionAccess.Read, new string[] { path },
		     false, false).Demand();
flag = InternalExists(path);

Comparing with FileInfo. When you create a new FileInfo with the constructor, it also uses the Path.GetFullPathInternal method and creates a new FileIOPermission object. For this reason, both approaches share the same performance characteristics.

Summary

Here we saw how you can use the File.Exists method to test for file existence in your C# programs. This is a simple but very powerful method that can really help improve programs by shielding them from disk IO exceptions. You will likely use File.Exists in almost every program that uses disk IO, as it is convenient and easy to quickly scan and check for correctness.

File Handling
.NET