How to Check If File Exists in C#/CSharp

To check if file exists in C#/CSharp, we make use of static function Exists of File class.  This will return a boolean value.  Example is given below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.IO;
namespace Hello_World
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\file.txt";
if(File.Exists(path))
{
Console.WriteLine("File Exists: Yes!");
}
else
{
Console.WriteLine("File Exists: No!");
}
}
}
}
using System; using System.IO; namespace Hello_World { class Program { static void Main(string[] args) { string path = @"C:\file.txt"; if(File.Exists(path)) { Console.WriteLine("File Exists: Yes!"); } else { Console.WriteLine("File Exists: No!"); } } } }
using System;
using System.IO;

namespace Hello_World
{

    class Program
    {
        static void Main(string[] args)
        {            
            string path = @"C:\file.txt";
            if(File.Exists(path))
            {
                Console.WriteLine("File Exists: Yes!");
            }
            else
            {
                Console.WriteLine("File Exists: No!");
            }
        }               
    }
}