How can I check in C# if a specific path is a directory?
4 Answers
Try the following
bool isDir = Directory.Exists(somePath)
Note that this doesn't truly tell you if a directory exists though. It tells you that a directory existed at some point in the recent past to which the current process had some measure of access. By the time you attempt to access the directory it could already be deleted or changed in some manner as to prevent your process from accessing it.
In short it's perfectly possible for the second line to fail because the directory does not exist.
if ( Directory.Exists(somePath) ) {
var files = Directory.GetFiles(somePath);
}
I wrote a blog entry on this subject recently is worth a read if you are using methods like Directory.Exists to make a decision

- 733,204
- 149
- 1,241
- 1,454
You could also do:
FileAttributes attr = File.GetAttributes(@"c:\Path\To\Somewhere");
if((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
//it's a directory
}

- 82,559
- 17
- 97
- 130
If the path exists, you can use: Directory.Exists
to tell whether it is a file or directory.
bool existsAndIsDirectory = Directory.Exists(path);
If the path does not exist, then there is no way to tell if the path is a file or a directory because it could be either.

- 3,071
- 5
- 30
- 51

- 339,232
- 124
- 596
- 636