Home Programs Check the Existence of a File in C#

Check the Existence of a File in C#

In this example we will show you how to check for the existence of a file in C#

Example

The existence of the file is checked using the File.Exist function with a Boolean variable. We then display a message depending on whether the file exists or not

You can change the code to select a file on your own system from J:\\csharp\\testfile.txt

using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo info = new FileInfo("J:\\csharp\\testfile.txt");
            bool exists = info.Exists;
            if (exists == true)
            {
                Console.WriteLine("The File Exists");
            }
            else
            {
                Console.WriteLine("File not found");
            }
            Console.Read();
        }
    }
}

 

You may also like