TheDeveloperBlog.com


C# File.Exists Method

File.Exists sees if a specific file exists. There are several ways of testing file existence. File.Exists is the easiest. It is the simplest way of checking that the file exists. It returns true or false.

BoolTrue, False

Example. First, the usage of File.Exists is 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.

Tip: To understand the next example, you have to imagine that the files tested actually exist or don't exist on the hard disk.

C# program that uses File Exists

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. This means you can either test it directly in an if-conditional statement or assign its result to a bool. Usually we just use it in an if-statement.

IfAssign Local Variables

Internals. 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. It 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 have similar performance.

FileInfo

Summary. We used the File.Exists method to test for file existence in a C# program. This is a simple but powerful method that helps improve programs by shielding them from disk IO exceptions.

Tip: You will likely use File.Exists in many programs. It is convenient and easy to scan and check for correctness.