windows 如何检查一条路径是否是另一条路径的子路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8091829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:27:09  来源:igfitidea点击:

How to check if one path is a child of another path?

c#.netwindowspath

提问by user626528

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

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

采纳答案by Captain Coder

This would be one way to go, you have path A and B, convert them to full paths with the Path.GetFullPath() function. Next check if one of the full paths is a starting substring of the other.

这将是一种方法,您有路径 A 和 B,使用 Path.GetFullPath() 函数将它们转换为完整路径。接下来检查一个完整路径是否是另一个的起始子串。

So that would be

所以那将是

if (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B)) ||
    Path.GetFullPath(B).StartsWith(Path.GetFullPath(A)))
   { /* ... do your magic ... */ }

回答by Charlie

Unfortunately it's not as simple as StartsWith.

不幸的是,它并不像StartsWith.

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

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

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;
}

回答by Oren Melzer

Any string-based solution is potentially subject to directory traversal attacksor correctness issues with things like trailing slashes. Unfortunately, the .NET Pathclass does not provide this functionality, however the Uriclass does, in the form of Uri.IsBaseOf().

任何基于字符串的解决方案都可能受到目录遍历攻击或尾部斜杠等正确性问题的影响。不幸的是,.NETPath类不提供此功能,但是Uri该类以Uri.IsBaseOf().

    Uri potentialBase = new Uri(@"c:\dir1\");

    Uri regular = new Uri(@"c:\dir1\dir2");

    Uri confusing = new Uri(@"c:\temp\..\dir1\dir2");

    Uri malicious = new Uri(@"c:\dir1\..\windows\system32\");

    Console.WriteLine(potentialBase.IsBaseOf(regular));   // True
    Console.WriteLine(potentialBase.IsBaseOf(confusing)); // True
    Console.WriteLine(potentialBase.IsBaseOf(malicious)); // False

回答by Siderite Zackwehdex

I've used an extension method like this:

我使用了这样的扩展方法:

    /// <summary>
    /// Check if a directory is the base of another
    /// </summary>
    /// <param name="root">Candidate root</param>
    /// <param name="child">Child folder</param>
    public static bool IsBaseOf(this DirectoryInfo root, DirectoryInfo child)
    {
        var directoryPath = EndsWithSeparator(new Uri(child.FullName).AbsolutePath);
        var rootPath = EndsWithSeparator(new Uri(root.FullName).AbsolutePath);
        return directoryPath.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase);
    }

    private static string EndsWithSeparator(string absolutePath)
    {
        return absolutePath?.TrimEnd('/','\') + "/";
    }

回答by techExplorer

In C# you can do it like this:

在 C# 中,你可以这样做:

string cp = Path.GetFullPath(childPath);
string pp = Path.GetFullPath(parentPath);

if(pp.StartsWith(cp))
    return true;
else
    return false;

回答by frankl5150

I have found that this works for windows:

我发现这适用于 Windows:

if (pathA.Equals(pathB, StringComparison.OrdinalIgnoreCase) ||
    pathA.StartsWith(pathB + "\", StringComparison.OrdinalIgnoreCase))

If your paths might have trailing characters, you could normalize them like this first:

如果您的路径可能有尾随字符,您可以先像这样将它们标准化:

pathA = Path.GetFullPath(pathA);
pathB = Path.GetFullPath(pathB);

回答by Akhil Gupta

Had the same issue. You can use StartWith()if you have the path as string

有同样的问题。StartWith()如果您将路径作为字符串,则可以使用

if (pathA.StartsWith (pathB + "\")) {

Though I am not sure if it is cross platform or not, but it does work on PC

虽然我不确定它是否跨平台,但它确实适用于 PC