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

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

问题描述

我处理目录和文件的树视图,用户可以选择一个文件或目录,然后用它做什么。这就要求我有一种方法,它执行不同的动作,如果他们选择了一个文件,或目录。

I am processing a TreeView of directories and files, users 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 if they have selected a file, or a directory.

目前,我正在做这样的事情,以确定该路径是文件或目录:

At the moment I am doing something like this to determine if 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! But I cannot find any .Net methods which I can ask "Is this path a directory or a file ?".

有什么建议?

谢谢!

推荐答案

从的如何判断路径是文件或目录

// 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或更高版本(和最高性能并不重要),你可以写code在一个更清洁的方式:

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:

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

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

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