检查目录是否可以在C#中访问?

可能重复:
.NET – 检查目录是否可访问而无需exception处理

我使用.NET 3.5和C#在Visual Studio 2010中创建一个小文件浏览器,我有这个函数来检查目录是否可访问:

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

但我认为对于大目录,尝试让所有子目录检查目录是否可访问可能会很慢。 我正在使用此function来防止在尝试探索受保护文件夹或没有光盘的cd / dvd驱动器时出错(“设备未就绪”错误)。

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

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

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