File.Exists. This C# method determines if a specific file exists. There are several ways of testing file existence. File.Exists is the easiest.
C# method info. Exists() is the simplest way of checking that the file exists. This can prevent an exception from being thrown. File.Exists returns true or false.
An example. The usage of File.Exists is straightforward. To understand the example, you have to imagine that the files tested actually exist or don't exist on the hard disk.
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);
}
}The file exists.
The file exists.
False
Internals. The file existence method is well-known in many languages. This code shows how the File.Exists method is implemented in .NET—it calls into the InternalExists method.
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.
A 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2021 (rewrite).