Check if a File exists using C#

If you want to check if a specific file exists on a local machine at a particular path using C# programming language, you can do so by using the File.Exists() method.

To use this first you need to import the System.IO namespace.

using System.IO;

Next, below is a sample code that checks if a file exists, first in the same directory and then in some different directory, in case of any doubts/suggestion feel free to use the comments section. Cheers !

using System;  
using System.IO;

class Program  
{  
    static void Main()  
    {

        // See if this file exists in the SAME DIRECTORY.  
        if (File.Exists("Yasser.txt"))  
        {  
            Console.WriteLine("The file exists.");  
        }  

        // See if this file exists in the C:\YS\ directory.  
        if (File.Exists(@"C:\YS\Yasser.txt"))  
        {  
            Console.WriteLine("The file exists.");  
        }

    }  
}  

You can find the documentation here on MSDN.