Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to check if a file exists in C#

Siddharth Singh

The File class in the System.IO namespace provides the Exists() method that checks the existence of a file. This method takes the path of the file as a string input and return true if the file exists at the specified path on the disk; otherwise, it returns false.

Syntax

public static bool Exists (string? path);

The Exists() method will return false if:

  • The input file does not exist.
  • The input path is null.
  • The input path is an empty string.
  • The input path is invalid.
  • The caller does not have sufficient permissions.
  • The input path is a directory.

Code example

In the below example, the file test.txt is existing in the current directory.

The File.Exists() method returns true for this path and the program prints File test.txt exists.

main.cs
test.txt
using System;
using System.IO;

class HelloWorld
{
    static void Main()
    {
       string path = "test.txt";
       if(File.Exists(path))
       {
           Console.WriteLine($"File {path} exists!");
       } else 
       {
            Console.WriteLine($"File {path} does not exist!");
       }
    }
}

Note: This method should not be used for validating a path since it only checks the existence of the file. Therefore, it does not throw an exception for invalid paths or any other error scenarios.

RELATED TAGS

c#
communitycreator
RELATED COURSES

View all Courses

Keep Exploring