C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To understand the next example, you have to imagine that the files tested actually exist or don't exist on the hard disk.
Returns: The File.Exists method returns a Boolean value. We can test it in an if-conditional statement or assign its result to a bool.
IfBool MethodC# 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);
}
}
Output
The file exists.
The file exists.
False
Part of File.Exists method: C#
path = Path.GetFullPathInternal(path);
new FileIOPermission(FileIOPermissionAccess.Read, new string[] { path },
false, false).Demand();
flag = InternalExists(path);
Tip: You will likely use File.Exists in many programs. It is convenient and easy to scan and check for correctness.