如何检查一条路径是否是另一条路径的子路径? [英] How to check if one path is a child of another path?

查看:26
本文介绍了如何检查一条路径是否是另一条路径的子路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查一条路径是否是另一条路径的子路径?
仅仅检查子字符串不是一种方法,因为可以有诸如 .和..等

How to check if one path is a child of another path?
Just checking for substring is not a way to go, because there can items such as . and .., etc

推荐答案

遗憾的是它不像 StartsWith 那样简单.

Unfortunately it's not as simple as StartsWith.

这是一个更好的答案,改编自 这个 重复的问题.为了便于使用,我已将其作为扩展方法.同样使用暴力catch,因为几乎任何访问文件系统的方法都可能因用户权限而失败.

Here's a better answer, adapted from this duplicate question. I've made it an extension method for ease of use. Also using a brute-force catch as just about any method that accesses the file system can fail based on user permissions.

public static bool IsSubDirectoryOf(this string candidate, string other)
{
    var isChild = false;
    try
    {
        var candidateInfo = new DirectoryInfo(candidate);
        var otherInfo = new DirectoryInfo(other);

        while (candidateInfo.Parent != null)
        {
            if (candidateInfo.Parent.FullName == otherInfo.FullName)
            {
                isChild = true;
                break;
            }
            else candidateInfo = candidateInfo.Parent;
        }
    }
    catch (Exception error)
    {
        var message = String.Format("Unable to check directories {0} and {1}: {2}", candidate, other, error);
        Trace.WriteLine(message);
    }

    return isChild;
}

这篇关于如何检查一条路径是否是另一条路径的子路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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