Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is path a directory? [duplicate]

Tags:

c#

io

How can I check in C# if a specific path is a directory?

like image 432
Alon Gubkin Avatar asked Sep 09 '25 15:09

Alon Gubkin


1 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

  • http://blogs.msdn.com/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx
like image 197
JaredPar Avatar answered Sep 12 '25 05:09

JaredPar