.NET如何检查路径是一个文件,而不是一个目录? [英] .NET How to check if path is a file and not a directory?

查看:175
本文介绍了.NET如何检查路径是一个文件,而不是一个目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:\Test\foo.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;

这篇关于.NET如何检查路径是一个文件,而不是一个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆