C# 路径是目录吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1896973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:42:48  来源:igfitidea点击:

Is path a directory?

c#io

提问by Alon Gubkin

How can I check in C# if a specific path is a directory?

如果特定路径是目录,我如何检查 C#?

采纳答案by JaredPar

Try the following

尝试以下

bool isDir = Directory.Exists(somePath) 

Note that this doesn't truly tell you if a directory exists though. It tells you that a directory existed at some point in the recent past to which the current process had some measure of access. By the time you attempt to access the directory it could already be deleted or changed in some manner as to prevent your process from accessing it.

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

In short it's perfectly possible for the second line to fail because the directory does not exist.

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

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

I wrote a blog entry on this subject recently is worth a read if you are using methods like Directory.Exists to make a decision

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

回答by Brian R. Bondy

If the path exists, you can use: Directory.Existsto tell whether it is a file or directory.

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

bool existsAndIsDirectory = Directory.Exists(path);

If the path does not exist, then there is no way to tell if the path is a file or a directory because it could be either.

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

回答by John Boker

You could also do:

你也可以这样做:

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

回答by Webleeuw

You can also check for the file attributes by File.GetAttributes()(of course, only if the file/directory exists). The FileAttributestype has a value named Directorywhich indicates if the path is a directory.

您还可以通过File.GetAttributes()(当然,仅当文件/目录存在时)检查文件属性。该FileAttributes类型具有一个值Directory,该值指示路径是否为目录。