【发布时间】:2010-02-25 18:46:28
【问题描述】:
我需要浏览计算机上的各种目录(通过 DirectoryInfo)。其中一些不可访问,并且发生 UnauthorizedAccessException。如何在不捕获异常的情况下检查目录访问?
【问题讨论】:
标签: .net directoryinfo
我需要浏览计算机上的各种目录(通过 DirectoryInfo)。其中一些不可访问,并且发生 UnauthorizedAccessException。如何在不捕获异常的情况下检查目录访问?
【问题讨论】:
标签: .net directoryinfo
您需要使用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.
}
更新:(跟随 cmets)
FileIOPermission处理的是安全策略而不是文件系统权限,所以你需要使用DirectoryInfo.GetAccessControl。
【讨论】:
Granting of permissions is determined by policy and is different from a demand subject to overrides, such as an assert. Also, IsGranted only tests the grant of the calling code assembly, independent of other callers on the stack.
no read permission rights 时抛出异常。但仍有可能列出文件夹内容的权利。在这种情况下 GetAccessControl() 将无济于事。
简单地说,你不能。无法检查目录是否可访问,您只能确定它是否可访问。原因是一旦检查完成,权限可能会更改并使您的检查无效。您可以实施的最可靠策略是访问目录并捕获UnauthorizedAccessException。
我最近写了一篇关于这个主题的博客文章,这里有一些详细的介绍
【讨论】:
你可以只做一个简单的小布尔函数,并让一个目录信息变量尝试从给定路径获取目录。如果没有问题,则返回true,如果异常是句柄,则返回false,或者将您的异常子句分解为子异常并获取错误代码。
【讨论】: