C# File.Exists MethodDetermine if a file is present on the disk with the File.Exists method from the System.IO namespace.
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.
True, 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.
Return The File.Exists method returns a Boolean value. We can test it in an if-conditional statement or assign its result to a bool.
Bool Method
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); } }
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.
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.
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.
© 2007-2021 sam allen.
see site info on the changelog.