.NET 如何检查路径是否是文件而不是目录?

标签 .net file directory

我有一个路径,我需要确定它是目录还是文件。

这是确定路径是否是文件的最佳方法吗?

string file = @"C:\Test\foo.txt";

bool isFile = !System.IO.Directory.Exists(file) && 
                         System.IO.File.Exists(file);

对于目录,我会颠倒逻辑。

string directory = @"C:\Test";

bool isDirectory = System.IO.Directory.Exists(directory) && 
                            !System.IO.File.Exists(directory);

如果两者都不存在,那么我不会去做任何一个分支。所以假设它们都存在。

最佳答案

用途:

System.IO.File.GetAttributes(string path)

并检查返回的FileAttributes结果是否包含值FileAttributes.Directory:

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
                 == FileAttributes.Directory;

关于.NET 如何检查路径是否是文件而不是目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/439447/

相关文章:

c# - 设置中的自定义类型

c# - 同时执行两个独立的方法

asp.net - 使用哪个 .net 版本? Web 配置中的那个还是构建时使用的那个?

linux - 在守护进程使用时监视日志文件

python - 如何将 JSON 文件的内容放入响应中

java - 在各种平台上创建文件的常见位置(非用户特定)

.net - 名称中带有句点的 BCP 数据库

file - encfs 未挂载文件夹

java - 如何删除Windows 7中的隐藏文件

c - 如何获得 C 语言的目录列表?