Check if a File exists in C#


Use 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#.

Example

 Live Demo

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!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements