239

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

Daren Thomas
  • 67,947
  • 40
  • 154
  • 200

6 Answers6

366

Use:

File.Exists(path)

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

Edit: In System.IO

Daniel Jennings
  • 6,304
  • 3
  • 32
  • 42
  • 20
    File.Exists(path) returns false even if the file exists BUT caller lacks permission to read it. Is there a different way to handle this kind of situations and check whether a file exists even if the caller cannot read it? – ADTC Mar 05 '12 at 08:06
  • 3
    @ADTC: from a security point of view it sounds normal that it works that way, from a developer point of view, it may make things more complicated. Do you get an exception in that case if you try to create a file? – user276648 Mar 04 '13 at 03:50
  • I'm sorry, I'm unable to answer your question now as this was on an old project. I suppose it should throw an exception since a lack of reading permission should mean a lack of over-writing permission too. But not sure. – ADTC Mar 05 '13 at 03:46
  • 2
    @ADTC just stumbled by and thought I might mention drop-box directories. Those can be set up where you have create or write permission but no read permission. Not that it is relevant to this question directly, just that they are not as odd as one might think. – Ukko May 30 '13 at 19:29
  • 1
    Side note: File.Exists returns False on Google Drive File Stream G: drive, if the casing of path does not exactly match what is actually on G:. Usually on any physical drive casing does not matter, so I wonder, is there something amiss with the Exists method? – CTZStef Sep 18 '17 at 12:48
  • What if the file name contains a wildcard? – Kappacake Aug 07 '19 at 13:46
  • 1
    @CTZStef that's the quirk of the google's virtual drive rather than of the framework method. – Eugene Mayevski 'Callback Nov 05 '19 at 09:38
77

System.IO.File:

using System.IO;

if (File.Exists(path)) 
{
    Console.WriteLine("file exists");
} 
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Peter Hoffmann
  • 56,376
  • 15
  • 76
  • 59
30

System.IO.File.Exists(path)

msdn

pirho
  • 2,972
  • 4
  • 23
  • 17
8

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);
Community
  • 1
  • 1
shivi
  • 147
  • 2
  • 12
1

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

Jesus Hedo
  • 119
  • 1
  • 1
  • 10
0
File.Exists(Path.Combine(_workDir, _file));
Mike
  • 185
  • 1
  • 2
  • 13
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Dec 30 '22 at 20:06