se the File.exists method in C# to check if a file exits in C# or not.
Firstly, check whether the file is present in the current directory.
if (File.Exists("MyFile.txt")) {
Console.WriteLine("The file exists.");
}
After that check whether the file exist in a directory or not.
if (File.Exists(@"D:\myfile.txt")) {
Console.WriteLine("The file exists.");
}
Let us see the complete example to check if a file exists in C#.
using System;
using System.IO;
class Demo {
static void Main() {
if (File.Exists("MyFile.txt")) {
Console.WriteLine("File exists...");
} else {
Console.WriteLine("File does not exist in the current directory!");
}
if (File.Exists(@"D:\myfile.txt")) {
Console.WriteLine("File exists...");
} else {
Console.WriteLine("File does not exist in the D directory!");
}
}
}
Output
File does not exist in the current directory!
File does not exist in the D directory!