【问题标题】:.NET - Check if directory is accessible without exception handling.NET - 检查目录是否可以在没有异常处理的情况下访问
【发布时间】:2010-02-25 18:46:28
【问题描述】:

我需要浏览计算机上的各种目录(通过 DirectoryInfo)。其中一些不可访问,并且发生 UnauthorizedAccessException。如何在不捕获异常的情况下检查目录访问?

【问题讨论】:

    标签: .net directoryinfo


    【解决方案1】:

    您需要使用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

    【讨论】:

    • 我尝试了以下操作: Dim readPermission As New FileIOPermission(FileIOPermissionAccess.Read, "C:\Users\Admin\Documents\My Pictures") 上述目录访问尝试产生“访问被拒绝”,但是“ SecurityManager.IsGranted(readPermission)" 总是返回 true。
    • 来自msdn.microsoft.com/en-us/library/…: 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.
    • 这不是正确的答案。 FileIOPermission 处理 CAS,而不是文件系统。换句话说,.NET 安全策略是否允许访问。您可以拥有 CAS 访问权限,但 Windows 仍然可以拒绝它。需要 DirectoryInfo.GetAccessControl()。
    • @HansPassant DirectoryInfo.GetAccessControl() 可能会在授予no read permission rights 时抛出异常。但仍有可能列出文件夹内容的权利。在这种情况下 GetAccessControl() 将无济于事。
    • 以防万一有人感兴趣,我用GetAccessControl here做了一个小sn-p
    【解决方案2】:

    简单地说,你不能。无法检查目录是否可访问,您只能确定它是否可访问。原因是一旦检查完成,权限可能会更改并使您的检查无效。您可以实施的最可靠策略是访问目录并捕获UnauthorizedAccessException

    我最近写了一篇关于这个主题的博客文章,这里有一些详细的介绍

    【讨论】:

      【解决方案3】:

      你可以只做一个简单的小布尔函数,并让一个目录信息变量尝试从给定路径获取目录。如果没有问题,则返回true,如果异常是句柄,则返回false,或者将您的异常子句分解为子异常并获取错误代码。

      【讨论】:

        猜你喜欢
        • 2011-06-11
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多