代码之家  ›  专栏  ›  技术社区  ›  Alon Gubkin

路径是目录吗?[复制品]

io c#
  •  24
  • Alon Gubkin  · 技术社区  · 15 年前

    这个问题已经有了答案:

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

    4 回复  |  直到 7 年前
        1
  •  37
  •   JaredPar    15 年前

    尝试以下操作

    bool isDir = Directory.Exists(somePath) 
    

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

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

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

    我最近写了一篇关于这个主题的博客,如果你使用目录之类的方法,值得一读。

        2
  •  30
  •   John Boker    15 年前

    你也可以这样做:

    FileAttributes attr = File.GetAttributes(@"c:\Path\To\Somewhere");
    if((attr & FileAttributes.Directory) == FileAttributes.Directory)
    {
        //it's a directory
    }
    
        3
  •  7
  •   Irshad huMpty duMpty    7 年前

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

        4
  •  6
  •   Irshad huMpty duMpty    7 年前

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

    bool existsAndIsDirectory = Directory.Exists(path);
    

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