检查目录是在C#访问?

问题描述:

可能重复:结果
NET - 检查目录也不例外处理

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

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



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

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).

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

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

据 MSDN ,目录。存在应该返回false,如果你不具备读取权限的目录。但是,您可以使用 Directory.GetAccessControl 了解这一点。例如:

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