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

C#.NetIo

C# Problem Overview


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#.

C# Solutions


Solution 1 - C#

Use:

File.Exists(path)

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

Edit: In System.IO

Solution 2 - C#

System.IO.File:

using System.IO;

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

Solution 3 - C#

System.IO.File.Exists(path)

msdn

Solution 4 - C#

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaren ThomasView Question on Stackoverflow
Solution 1 - C#Daniel JenningsView Answer on Stackoverflow
Solution 2 - C#Peter HoffmannView Answer on Stackoverflow
Solution 3 - C#pirhoView Answer on Stackoverflow
Solution 4 - C#shiviView Answer on Stackoverflow
Solution 5 - C#Jesus HedoView Answer on Stackoverflow