How to Check if a File Exists by Using C#

When you need to check whether a particular file exists on a specified path, you can use File.Exists(string) method of C#. This method requires full file name i.e. file name along with its extension and the path where it is located.

Full File Name = DirectoryPath\FileName.extension

If TestFile.txt is located in directory D:\TEST\

Then the full file name will be D:\TEST\TestFile.txt

Let’s understand this by below given C# example.

You need to use System.IO namespace in your code and write the code as given below.

using System;
using System.IO;
 
class CFD 
{
    public static void Main()
    {
     string filename = @“D:\TEST\”;
     sting filePath = “TestFile.txt”;
        // Checking the existence of the specified
        if (File.Exists(filename + filePath)) 
        {
            Console.WriteLine("File Exists on path");
        }
        else 
        {
            Console.WriteLine("File does not exists on path");
        }
    }
}

When you run above code, the output will be “File Exists on path” if the file with TestFile.txt is available on the specified path (D:\TEST\) and the output will be “File does not exists on path” if the file is not available on the path.

Leave a Reply