Leonardo
Leonardo

Reputation: 11401

Reliable Directory.Exists using C#

According to this MSDN article, Directory.Exists can return false negatives (the directory exists, but you can't read it or similar). I was wondering if there's a similar method that, instead of returning true or false, returns something more informative... like "access denied" or maybe "path too long"...

Upvotes: 0

Views: 3286

Answers (3)

Austin_Anderson
Austin_Anderson

Reputation: 940

source

this code can differentiate between if a file actually exists, and if the file does but the user doesn't have access

enum ExistState { exist, notExist, inaccessible };

void Check(string name) {
    DirectoryInfo di = new DirectoryInfo(name);
    ExistState state = ExistState.exist;
    if (!di.Exists) {
        try {
            if ((int)di.Attributes == -1) {
                state = ExistState.notExist;
            }
        } catch (UnauthorizedAccessException) {
            state = ExistState.inaccessible;
        }
    }
    Console.WriteLine("{0} {1}", name, state);
}

explanation from the source
"The DirectoryInfo.Attributes property is incorrectly documented and does not raise the FileNotFound or DirectoryNotFound exceptions but instead returns the error value from the underlying win api function, which is 0xFFFFFFFF or -1.

If a path exists but access is disallowed then an attempt to retrieve the attributes will throw an exception.

If the path does not exist then the attributes will be -1."

Upvotes: 0

juharr
juharr

Reputation: 32296

You could try to create a DirectoryInfo object instead. The constructor should throw exceptions if the path is invalid or if the user does not have access. You would still have to check if it exists though.

try
{
    var di = new DirectoryInfo(path);
    if(di.Exists)
    {
        //The directory exists
    }
    else
    {
        //The path is valid, but does not exist.
    }
}
catch(Exception e)
{
    //The path is invalid or user does not have access.
}

Upvotes: 1

msporek
msporek

Reputation: 1197

There is a Directory.GetAccessControl() method which you can use to get listable but unreadable directories:

public static bool DirectoryVisible(string path)
{
    try
    {
        Directory.GetAccessControl(path);
        return true;
    }
    catch (UnauthorizedAccessException)
    {
        return true;
    }
    catch
    {
        return false;
    }
}

You can also utilize the DirectoryInfo class. It comes with Exists property, and Attributes property. If there is an UnauthorizedAccessException thrown when you access the Attributes property, then it means that you cannot access the directory.

Upvotes: 1

Related Questions