开发者

Can I tell if a string corresponds to either a file or a directory in .NET? [duplicate]

This question already has answers here: .NET How to check if path is a file and not a directory? (8 answers) Closed 9 years ago.

If I have a string, I know I can use If System.IO.File.Exists(mystring) or System.IO.Directory.Exists(mystring) to see which it is. Is there a method I can use to make a single call to determine which type it is? Since, at least in Windows, you can't have both a file and a directory 开发者_Python百科with the same name, it seems like there should be a function that accepts a string and returns either "Folder", "File", or "Nothing".

I'm currently doing this, but it doesn't seem like the best way to do it:

If Directory.Exists(mystring) Then
   ' It's a folder
ElseIf File.Exists(mystring) Then
   ' It's a file
Else
   ' It's neither - doesn't exist
End If


Use the System.IO.File.GetAttributes() method. The returned FileAttributes enum has a flag that indicates if it's a directory.

string path = @"C:\Program Files";
if( (int)(File.GetAttributes( path ) & FileAttributes.Directory) != 0 )
{
   // .. it's a directory...
}

This works best if you know the path to exist. If the path is invalid, you will get an exception. If you don't know that the path exists, your approach of first calling Directory.Exists() followed by File.Exists() is probably better.

You can, of course, write your own method to wrap this logic up together, so you don't have to repeat it in more than one place.


Another solution might be:

if ( !string.IsNullOrEmpty( Path.GetFileName(path) ) )
{
   //it's a file
}
else if ( !string.IsNullOrEmpty( Path.GetDirectory(path) )
{
   //it's a directory
}

This is obviously not foolproof nor will it in any way establish whether the given file or directory exists on the disk. It will only determine if the path has something that looks like a filename in it. It obviously will not handle oddball situations like a directory called "foo.com". However, if you are looking for something that is pretty close that will lessen the odds of an exception, this might help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜