Check if directory is accessible in C#? [duplicate]

孤街浪徒 提交于 2019-12-17 12:22:23

问题


Possible Duplicate:
.NET - Check if directory is accessible without exception handling

Im making a small file explorer in Visual Studio 2010 with NET 3.5 and C#, and I have this function to check if a directory is accessible:

RealPath=@"c:\System Volume Information";
public bool IsAccessible()
{
    //get directory info
    DirectoryInfo realpath = new DirectoryInfo(RealPath);
    try
    {
        //if GetDirectories works then is accessible
        realpath.GetDirectories();                
        return true;
    }
    catch (Exception)
    {
        //if exception is not accesible
        return false;
    }
}

But I think with big directories it could be slow trying to get all sub directories to check if directory is accesible. Im using this function to prevent errors when trying to explore protected folders or cd/dvd drives without disc ("Device Not Ready" error).

Is there a better way (faster) to check if directory is accessible by the application (preferably in NET 3.5)?


回答1:


According to MSDN, Directory.Exists should return false if you don't have read access to the directory. However, you can use Directory.GetAccessControl for this. Example:

public static bool CanRead(string path)
{
    var readAllow = false;
    var readDeny = false;
    var accessControlList = Directory.GetAccessControl(path);
    if(accessControlList == null)
        return false;
    var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
    if(accessRules ==null)
       return false;

    foreach (FileSystemAccessRule rule in accessRules)
    {
        if ((FileSystemRights.Read & rule.FileSystemRights) != FileSystemRights.Read) continue;

        if (rule.AccessControlType == AccessControlType.Allow)
            readAllow = true;
        else if (rule.AccessControlType == AccessControlType.Deny)
            readDeny = true;
    }

    return readAllow && !readDeny;
}



回答2:


I think you are looking for the GetAccessControl method, the System.IO.File.GetAccessControl method returns a FileSecurity object that encapsulates the access control for a file.



来源:https://stackoverflow.com/questions/11709862/check-if-directory-is-accessible-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!