The File
class in the System.IO
namespace provides the Exists()
method that checks the existence of a file. This method takes the path of the file as a string input and return true if the file exists at the specified path on the disk; otherwise, it returns false.
public static bool Exists (string? path);
The Exists() method will return false
if:
null
.In the below example, the file test.txt is existing in the current directory.
The File.Exists()
method returns true for this path and the program prints File test.txt exists
.
using System;using System.IO;class HelloWorld{static void Main(){string path = "test.txt";if(File.Exists(path)){Console.WriteLine($"File {path} exists!");} else{Console.WriteLine($"File {path} does not exist!");}}}
Note: This method should not be used for validating a path since it only checks the existence of the file. Therefore, it does not throw an exception for invalid paths or any other error scenarios.