How to Check Whether a File Exists in C#
This tutorial will introduce methods to check whether a file exists in a specific path in C#.
Check Whether a File Exists in a Specific Path With the File.Exists(path)
Function in C#
The File.Exits(path)
function inside the System.IO
namespace is used to check whether a file exists in the given path
or not. The File.Exists(path)
function returns true
if there is a file in the path
, and returns false
if there is no file in the path
. The following code example shows us how we can check whether a file exists in a specified path with File.Exists()
function in C#.
using System;
using System.IO;
namespace check_whether_a_file_exists {
class Program {
static void Main(string[] args) {
string path = "C:\\Files\\file.txt";
bool result = File.Exists(path);
if (result == true) {
Console.WriteLine("File Found");
} else {
Console.WriteLine("File Not Found");
}
}
}
}
Output:
File Found
We passed the absolute path of the file.txt
file as a parameter to the File.Exists()
function to check whether the file exists in the path or not. If you use Windows, Iyouhave to use \\
as the path separator. The code prints File Found
because there is actually a file file.txt
inside the C:\\Files
directory.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn