C# File Exists

Summary: in this tutorial, you’ll learn how to check if a file exists in C# using the File.Exists() method.

Introduction to the C# File.Exists() method

The File.Exists() static method allows you to check if a file exists:

public static bool Exists (string? path);Code language: C# (cs)

In this syntax, the path specifies the file to check.

The File.Exists() method returns true if the caller has sufficient permissions for the file and the path represents the name of an existing file. Otherwise, it returns false.

The File.Exists() method also returns false if the path is null, a zero-length string, or invalid.

Note that you should not use the File.Exists() method to check if a path contains valid characters. Instead, you should use the Path.GetInvalidPathChars() method.

The File.Exists() method determines if a file exists or not. To check a directory, you can use the Directory.Exists() method instead.

C# File.Exists() method example

The following program demonstrates how to use the File.Exists() method to check if a readme.txt file exists:

using static System.Console;

string filename = @"C:\temp\readme.txt";

if (File.Exists(filename))
{
    WriteLine($"The file {filename} exists.");
}
else
{
    WriteLine($"The file {filename} doesn't exist.");
}Code language: C# (cs)

Output:

The file C:\temp\readme.txt exist.Code language: C# (cs)

Summary

  • Use C# File.Exists() method to check if a file exists.
Was this tutorial helpful ?