Daren Thomas
Daren Thomas

Reputation: 70344

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

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

Upvotes: 251

Views: 367673

Answers (6)

Mike
Mike

Reputation: 195

File.Exists(Path.Combine(_workDir, _file));

Upvotes: 0

Jesus Hedo
Jesus Hedo

Reputation: 129

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

Upvotes: 1

shivi
shivi

Reputation: 157

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Upvotes: 9

Peter Hoffmann
Peter Hoffmann

Reputation: 58714

System.IO.File:

using System.IO;

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

Upvotes: 80

Daniel Jennings
Daniel Jennings

Reputation: 6480

Use:

File.Exists(path)

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

Edit: In System.IO

Upvotes: 381

pirho
pirho

Reputation: 3042

System.IO.File.Exists(path)

msdn

Upvotes: 30

Related Questions