Coder Perfect

In C# /.NET, how do you check if a file exists?

Problem

In C#, I’d like to test a string containing a file path for its existence (similar to the -e test in Perl or the os.path.exists() in Python).

Asked by Daren Thomas

Solution #1

Use:

File.Exists(path)

MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

Edit: In System.IO

Answered by Daniel Jennings

Solution #2

System.IO.File:

using System.IO;

if (File.Exists(path)) 
{
    Console.WriteLine("file exists");
} 

Answered by Peter Hoffmann

Solution #3

System.IO.File.Exists(path)

msdn

Answered by pirho

Solution #4

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Answered by shivi

Solution #5

I use WinForms, and here is how I use File.Exists(string path):

public bool FileExists(string fileName)
{
    var workingDirectory = Environment.CurrentDirectory;
    var file = $"{workingDirectory}\{fileName}";
    return File.Exists(file);
}

The extension must be included in the filename, such as myfile.txt.

Answered by Jesus Hedo

Post is based on https://stackoverflow.com/questions/38960/how-to-find-out-if-a-file-exists-in-c-sharp-net