检查路径是文件还是目录的更好方法? [英] Better way to check if a Path is a File or a Directory?

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

问题描述

我正在处理目录和文件的 TreeView.用户可以选择一个文件或一个目录,然后用它做一些事情.这需要我有一种方法可以根据用户的选择执行不同的操作.

I am processing a TreeView of directories and files. A user can select either a file or a directory and then do something with it. This requires me to have a method which performs different actions based on the user's selection.

目前我正在做这样的事情来确定路径是文件还是目录:

At the moment I am doing something like this to determine whether the path is a file or a directory:

bool bIsFile = false;
bool bIsDirectory = false;

try
{
    string[] subfolders = Directory.GetDirectories(strFilePath);

    bIsDirectory = true;
    bIsFile = false;
}
catch(System.IO.IOException)
{
    bIsFolder = false;
    bIsFile = true;
}

我不禁觉得有更好的方法可以做到这一点!我希望找到一种标准的 .NET 方法来处理这个问题,但我一直没能做到.有没有这样的方法,如果没有,判断一个路径是文件还是目录最直接的方法是什么?

I cannot help to feel that there is a better way to do this! I was hoping to find a standard .NET method to handle this, but I haven't been able to do so. Does such a method exist, and if not, what is the most straightforward means to determine whether a path is a file or directory?

推荐答案

来自 如何判断路径是文件还是目录:

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:Temp");

//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

.NET 4.0+ 更新

根据下面的评论,如果您使用的是 .NET 4.0 或更高版本(并且最大性能并不重要),您可以以更简洁的方式编写代码:

Update for .NET 4.0+

Per the comments below, if you are on .NET 4.0 or later (and maximum performance is not critical) you can write the code in a cleaner way:

// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:Temp");

if (attr.HasFlag(FileAttributes.Directory))
    MessageBox.Show("Its a directory");
else
    MessageBox.Show("Its a file");

这篇关于检查路径是文件还是目录的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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