2

I can use os.path.exists() to check if the file exists or not with Python. What's the equivalent function in C#?

prosseek
  • 169,389
  • 197
  • 542
  • 840

3 Answers3

3

Surely you mean .NET, not C# :)

Try System.IO.File.Exists.

Seth
  • 42,464
  • 10
  • 85
  • 118
3

Both System.IO.File and System.IO.Directory has Exists.

bool dirExists = System.IO.Directory.Exists(@"C:\directory\");
bool fileExists = System.IO.File.Exists(@"C:\directory\file.txt");

And for an additional bonus: Note that for cross platform compatibility you should use for example System.IO.Path.Combine("c:", "directory", "file.txt");. This will automatically join the parts of the directory using System.IO.Path.DirectorySeparatorChar. Of course only Windows has C:, so you need to know what to use as the root of the drive.

Tedd Hansen
  • 11,595
  • 14
  • 59
  • 96
2
System.IO.File.Exists(@"c:\path\to\your\file.ext");
Kirk Woll
  • 73,473
  • 21
  • 178
  • 189