I can use os.path.exists() to check if the file exists or not with Python. What's the equivalent function in C#?
Asked
Active
Viewed 1,069 times
3 Answers
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