我需要浏览计算机上的各种目录(通过DirectoryInfo)。其中一些不可访问,并发生UnauthorizedAccessException。如何在不捕获异常的情况下检查目录访问?
答案 0 :(得分:11)
简单地说你不能。无法检查目录是否可访问,您可以确定它是否可访问。原因是,一旦检查完成权限,就可以更改并使检查无效。您可以实现的最可靠的策略是访问目录并捕获UnauthorizedAccessException
。
我最近写了一篇关于这个主题的博客文章,这里有一些细节
答案 1 :(得分:10)
您需要使用Security
命名空间。
请参阅this SO回答。
来自答案:
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
更新:(以下评论)
FileIOPermission
处理安全策略而非文件系统权限,因此您需要使用DirectoryInfo.GetAccessControl
。
答案 2 :(得分:-1)
你可以做一个简单的小布尔函数,并有一个目录信息变量尝试从给定的路径获取目录。如果没有问题,则返回true,如果异常处理,则返回false,或者将异常子句分解为子异常并获取错误代码。