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

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

问题描述

我正在处理目录和文件的 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?

推荐答案

p>从如何判断路径是否文件或目录

// 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天全站免登陆