我有一个路径,我需要确定它是否是一个目录或文件。
I have a path and I need to determine if it is a directory or file.
这是确定的路径是一个文件的最好方法?
Is this the best way to determine if the path is a file?
string file = @"C:Testfoo.txt";
bool isFile = !System.IO.Directory.Exists(file) &&
System.IO.File.Exists(file);
有关目录我会扭转的逻辑。
For a directory I would reverse the logic.
string directory = @"C:Test";
bool isDirectory = System.IO.Directory.Exists(directory) &&
!System.IO.File.Exists(directory);
如果两者都不存在的话,我不会去做任何分支。因此,假设他们都这样做存在。
If both don't exists that then I won't go do either branch. So assume they both do exists.
使用:
System.IO.File.GetAttributes(string path)
和检查FileAttributes 结果返回是否包含值 FileAttributes.Directory
:
and check whether the returned FileAttributes
result contains the value FileAttributes.Directory
:
bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
== FileAttributes.Directory;