【问题标题】:Is path a directory? [duplicate]路径是目录吗? [复制]
【发布时间】:2009-12-13 16:29:13
【问题描述】:

如果特定路径是目录,我如何在 C# 中签入?

【问题讨论】:

    标签: c# io


    【解决方案1】:

    试试下面的

    bool isDir = Directory.Exists(somePath) 
    

    请注意,这并不能真正告诉您目录是否存在。它告诉您在最近的某个时间点存在一个目录,当前进程可以访问该目录。当您尝试访问该目录时,它可能已经被删除或以某种方式更改,以防止您的进程访问它。

    简而言之,第二行完全有可能因为目录不存在而失败。

    if ( Directory.Exists(somePath) ) { 
      var files = Directory.GetFiles(somePath); 
    }
    

    我最近写了一篇关于这个主题的博客文章,如果你使用像 Directory.Exists 这样的方法来做出决定,值得一读

    【讨论】:

      【解决方案2】:

      你也可以这样做:

      FileAttributes attr = File.GetAttributes(@"c:\Path\To\Somewhere");
      if((attr & FileAttributes.Directory) == FileAttributes.Directory)
      {
          //it's a directory
      }
      

      【讨论】:

        【解决方案3】:

        您也可以通过File.GetAttributes()检查文件属性(当然,只有在文件/目录存在的情况下)。 FileAttributes 类型有一个名为 Directory 的值,它指示路径是否为目录。

        【讨论】:

          【解决方案4】:

          如果路径存在,可以使用:Directory.Exists判断是文件还是目录。

          bool existsAndIsDirectory = Directory.Exists(path);
          

          如果路径不存在,则无法判断路径是文件还是目录,因为它可能是。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-10
            • 2020-06-02
            • 2017-04-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-02
            相关资源
            最近更新 更多