【问题标题】:Reliable Directory.Exists using C#Reliable Directory.Exists 使用 C#
【发布时间】:2014-12-29 16:58:31
【问题描述】:

根据this MSDN article,Directory.Exists 可以返回假阴性(目录存在,但您无法阅读或类似情况)。我想知道是否有类似的方法,而不是返回 true 或 false,而是返回更多信息......比如“访问被拒绝”或“路径太长”......

【问题讨论】:

    标签: c# io directory


    【解决方案1】:

    您可以尝试创建一个DirectoryInfo 对象。如果路径无效或用户无权访问,构造函数应该抛出异常。你仍然需要检查它是否存在。

    try
    {
        var di = new DirectoryInfo(path);
        if(di.Exists)
        {
            //The directory exists
        }
        else
        {
            //The path is valid, but does not exist.
        }
    }
    catch(Exception e)
    {
        //The path is invalid or user does not have access.
    }
    

    【讨论】:

    • 我认为DirectoryInfo 构造函数不会为不存在或您无权访问的路径引发异常。至少,它没有在我刚刚运行的快速测试中。哦,但我现在看到您在谈论一条真正无效的路径,而不是一条不存在的路径。但是那对 OP 的测试有什么好处呢?
    • @adv12 检查指向 MSDN 文档的链接。你仍然需要检查它是否存在,就像我提到的那样。
    • 哦,我看到 OP 想要捕获诸如“路径太长”之类的错误,这会被构造函数捕获。
    【解决方案2】:

    有一个Directory.GetAccessControl() 方法可以用来获取可列出但不可读的目录:

    public static bool DirectoryVisible(string path)
    {
        try
        {
            Directory.GetAccessControl(path);
            return true;
        }
        catch (UnauthorizedAccessException)
        {
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    您也可以使用DirectoryInfo 类。它带有Exists 属性和Attributes 属性。如果访问Attributes属性时抛出了UnauthorizedAccessException,则表示无法访问该目录。

    【讨论】:

      【解决方案3】:

      source

      此代码可以区分文件是否实际存在,以及文件是否存在但用户无权访问

      enum ExistState { exist, notExist, inaccessible };
      
      void Check(string name) {
          DirectoryInfo di = new DirectoryInfo(name);
          ExistState state = ExistState.exist;
          if (!di.Exists) {
              try {
                  if ((int)di.Attributes == -1) {
                      state = ExistState.notExist;
                  }
              } catch (UnauthorizedAccessException) {
                  state = ExistState.inaccessible;
              }
          }
          Console.WriteLine("{0} {1}", name, state);
      }
      

      来源说明
      "DirectoryInfo.Attributes 属性记录不正确,不会引发 FileNotFound 或 DirectoryNotFound 异常,而是从底层 win api 函数返回错误值,即 0xFFFFFFFF 或 -1。

      如果存在路径但不允许访问,则尝试检索属性将引发异常。

      如果路径不存在,则属性将为-1。”

      【讨论】:

        猜你喜欢
        • 2012-02-08
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        • 2011-04-09
        • 1970-01-01
        • 2019-03-16
        • 2016-06-28
        • 2015-07-18
        相关资源
        最近更新 更多