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
  • 182,215
  • 215
  • 566
  • 871

3 Answers3

3

Surely you mean .NET, not C# :)

Try System.IO.File.Exists.

Seth
  • 45,033
  • 10
  • 85
  • 120
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
  • 12,074
  • 14
  • 61
  • 97
2
System.IO.File.Exists(@"c:\path\to\your\file.ext");
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195