为了账号安全,请及时绑定邮箱和手机立即绑定

检查路径是文件还是目录的更好方法?

检查路径是文件还是目录的更好方法?

开满天机 2019-10-05 14:48:53
我正在处理TreeView目录和文件。用户可以选择文件或目录,然后对其进行操作。这就要求我有一种根据用户的选择执行不同动作的方法。目前,我正在执行以下操作来确定路径是文件还是目录: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方法来处理此问题,但我一直未能做到。是否存在这种方法,如果不存在,那么确定路径是文件还是目录的最直接方法是什么?
查看完整描述

3 回答

?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

这是我的:


    bool IsPathDirectory(string path)

    {

        if (path == null) throw new ArgumentNullException("path");

        path = path.Trim();


        if (Directory.Exists(path)) 

            return true;


        if (File.Exists(path)) 

            return false;


        // neither file nor directory exists. guess intention


        // if has trailing slash then it's a directory

        if (new[] {"\\", "/"}.Any(x => path.EndsWith(x)))

            return true; // ends with slash


        // if has extension then its a file; directory otherwise

        return string.IsNullOrWhiteSpace(Path.GetExtension(path));

    }

它与其他人的答案相似,但不完全相同。


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 562 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信