【问题标题】:How to check effectively if one path is a child of another path in C#?如何有效地检查一条路径是否是 C# 中另一条路径的子路径?
【发布时间】:2014-05-05 10:57:06
【问题描述】:

我正在尝试确定一条路径是否是另一条路径的子路径。

我已经尝试过:

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

喜欢How to check if one path is a child of another path?帖子

但它不起作用。例如,如果我写“C:\files”和“C:\files baaa”,代码认为“C:\files baaa”是“C:\files”的子代,如果不是,它是只有C:。 当我尝试使用长路径和大量孩子时,问题真的很严重。

我也尝试了“如果包含\”...但仍然没有真正在所有的追逐中工作

我能做什么?

谢谢!

【问题讨论】:

  • 你是指直系子女还是后代?
  • "C:\files baaa" 不是有效路径,所以我不确定我是否理解问题
  • @Harrison 为什么不呢?您不在文件夹名称中使用空格? :S
  • @gitsitgo。啊,明白了。感谢您指出我的误解。

标签: c# .net windows path


【解决方案1】:

我需要知道文件夹 B 是否与文件夹 A 中的 OR 相同。

以下内容对我有用:

if (A.FullName.Contains(B.FullName))
{
// Path A is equal to or contained within path B. (B is a child of A)
}

【讨论】:

    【解决方案2】:

    C:\files不是File,是Directory。所以你可以试试这个:

    DirectoryInfo A = new DirectoryInfo(Path.GetFullPath("firstPath"));
    DirectoryInfo B = new DirectoryInfo(Path.GetFullPath("secondPath"));
    
    if( B.Parent.FullName == A.FullName || A.Parent.FullName == B.FullName )
    

    如果您不是在寻找直接的亲子关系,您可以尝试:

    if (Directory
        .GetDirectories(A.FullName,"*",SearchOption.AllDirectories)
        .Contains(B.FullName) ||
    
         Directory
        .GetDirectories(B.FullName, "*", SearchOption.AllDirectories)
        .Contains(A.FullName))
    

    【讨论】:

      【解决方案3】:

      试试这个:

      if (!Path.GetFullPath(A).TrimEnd(Path.DirectorySeparatorChar).Equals(Path.GetFullPath(B).TrimEnd(Path.DirectorySeparatorChar), StringComparison.CurrentCultureIgnoreCase)
          && (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B) + Path.DirectorySeparatorChar, StringComparison.CurrentCultureIgnoreCase)
          || Path.GetFullPath(B).StartsWith(Path.GetFullPath(A) + Path.DirectorySeparatorChar, StringComparison.CurrentCultureIgnoreCase)))
         { /* ... do your magic ... */ }
      

      【讨论】:

      • 谢谢。我试过 Path.GetFullPath(listBoxItem.ToString()) + "\\") 并且似乎工作。
      • 如果 B ~= A 不会返回 true 吗?即 "C:\files" 和 "C:\files\\\" 因为它们都指向同一个文件夹,我相信在上面的代码中会 eval 为 true?
      • 是的,如果 A 和 B 指向同一个文件夹 true 将被返回。通过检查它们的完整路径的相等性很容易避免。我将更新示例。谢谢。
      • 好吧,在我的代码中,我要做的第一件事是删除路径开头和结尾的“\\”,将“/”转换为“\”和其他类似的检查。该代码对我有用,但如果你想改进它,是的,你可以:D 谢谢!
      猜你喜欢
      • 2011-12-26
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多