Jar*_*Par 37
请尝试以下方法
bool isDir = Directory.Exists(somePath)
Run Code Online (Sandbox Code Playgroud)
请注意,这并不能真正告诉您目录是否存在.它告诉您最近过去某个时刻存在一个目录,当前进程有一定程度的访问权限.当您尝试访问目录时,它可能已经以某种方式被删除或更改,以防止您的进程访问它.
简而言之,第二行完全有可能失败,因为目录不存在.
if ( Directory.Exists(somePath) ) {
var files = Directory.GetFiles(somePath);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用Directory.Exists等方法做出决定,我最近写了一篇关于这个主题的博客文章,值得一读
Joh*_*ker 30
你也可以这样做:
FileAttributes attr = File.GetAttributes(@"c:\Path\To\Somewhere");
if((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
//it's a directory
}
Run Code Online (Sandbox Code Playgroud)
您还可以检查文件属性File.GetAttributes()
(当然,仅当文件/目录存在时).该FileAttributes
类型具有一个名为value的值Directory
,指示该路径是否为目录.
如果路径存在,您可以使用:Directory.Exists
来判断它是文件还是目录.
bool existsAndIsDirectory = Directory.Exists(path);
Run Code Online (Sandbox Code Playgroud)
如果路径不存在,则无法判断路径是文件还是目录,因为它可能是.