Summary: in this tutorial, you’ll learn how to check if a file exists in C# using the method.File.Exists()
Introduction to the C# File.Exists() method
The static method allows you to check if a file exists:File.Exists()
public static bool Exists (string? path);Code language: C# (cs)In this syntax, the path specifies the file to check.
The 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.File.Exists()
The method also returns File.Exists()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 method determines if a file exists or not. To check a directory, you can use the File.Exists() method instead.Directory.Exists()
C# File.Exists() method example
The following program demonstrates how to use the method to check if a File.Exists()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#
method to check if a file exists.File.Exists()