Check Whether a File Exists in C#

Check Whether a File Exists in C#

Muhammad Maisam Abbas Mar-21, 2021 Mar-10, 2021 Csharp Csharp File

This tutorial will introduce methods to check whether a file exists in a specific path in C#.

Check Whether a File Exists in a Specific Path With the File.Exists(path) Function in C#

The File.Exits(path) function inside the System.IO namespace is used to check whether a file exists in the given path or not. The File.Exists(path) function returns true if there is a file in the path, and returns false if there is no file in the path. The following code example shows us how we can check whether a file exists in a specified path with File.Exists() function in C#.

using System;
using System.IO;

namespace check_whether_a_file_exists
    class Program
        static void Main(string[] args)
            string path = "C:\\Files\\file.txt";
            bool result = File.Exists(path);
            if (result == true)
                Console.WriteLine("File Found");
                Console.WriteLine("File Not Found");


File Found

We passed the absolute path of the file.txt file as a parameter to the File.Exists() function to check whether the file exists in the path or not. If you use Windows, Iyouhave to use \\ as the path separator. The code prints File Found because there is actually a file file.txt inside the C:\\Files directory.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.


Related Article - Csharp File

  • Get File Name From the Path in C#
  • Rename a File in C#
  • Download a File From a URL in C#
  • C# Read a Text File Line by Line
  • Read PDF File in C#
  • Read Embedded Resource Text File in C#