-->

检查目录是C#访问? [重复](Check if directory is accessible

2019-06-26 14:46发布

可能重复:
.NET -检查目录是没有异常处理访问

林做一个小的文件浏览器在Visual Studio 2010与.NET 3.5和C#,我要检查这个功能,如果一个目录可访问:

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;
    }
}

但我认为有很大的目录可能是缓慢试图让所有子目录检查,如果目录是入店。 即时通讯使用此功能,防止错误努力探索保护的文件夹或CD / DVD驱动器无光盘(“设备未准备好”的错误)时。

有没有更好的办法(快),以检查是否目录可访问应用程序(最好是在.NET 3.5)?

Answer 1:

根据MSDN , Directory.Exists应该返回false,如果你没有到该目录的读取访问。 但是,您可以使用Directory.GetAccessControl这一点。 例:

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;
}


Answer 2:

我认为你正在寻找GetAccessControl法, System.IO.File.GetAccessControl方法返回一个封装为一个文件的访问控制FileSecurity对象。



文章来源: Check if directory is accessible in C#? [duplicate]