File.Exists MethodDetermine if a file is present on the disk with the File.Exists method from the System.IO namespace.
This page was last reviewed on Nov 17, 2021.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2021 (rewrite).
© 2007-2024 Sam Allen.