How to find out if a file exists in C# / .NET?

198

I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#.

This question is tagged with c# .net io

~ Asked on 2008-09-02 07:18:48

5 Answers


316

Use:

File.Exists(path)

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

Edit: In System.IO

~ Answered on 2008-09-02 07:19:51


57

System.IO.File:

using System.IO;

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

~ Answered on 2008-09-02 07:22:11


26

System.IO.File.Exists(path)

msdn

~ Answered on 2008-09-02 07:21:07


7

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

~ Answered on 2014-03-09 08:30:24


0

I use WinForms and my way to use File.Exists(string path) is the next one:

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

fileName must include the extension like myfile.txt

~ Answered on 2021-01-14 14:47:39


Most Viewed Questions: