本文介绍了.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: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;

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

08-20 11:27
查看更多