5

I am trying to determine if one path is a child of another path.

I already tried with:

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

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

But it doesn't work. For example if I write "C:\files" and "C:\files baaa" the code thinks that the "C:\files baaa" is a child of "C:\files", when it isn't, it is only of C:. The problem is really heavy when I try with long paths, with an amount of childs.

I also tried with "if contains \"... but still not really working in all the chases

What can I do?

Thanks!

Community
  • 1
  • 1
user3108594
  • 225
  • 2
  • 5
  • 13

3 Answers3

6

Try this:

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 ... */ }
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • Thanks. I tried Path.GetFullPath(listBoxItem.ToString()) + "\\") and seems to work. – user3108594 Mar 26 '14 at 19:35
  • Wouldn't that return true if B ~= A? i.e. "C:\files" and "C:\files\\\" since both point to the same folder, and I believe will eval to true in the above code? – LB2 Mar 26 '14 at 19:42
  • Yup, if A and B points to the same folder `true` will be returned. It's easy to avoid by checking the equality of their full paths. I'm going to update the sample. Thank you. – Dmitry Mar 26 '14 at 19:52
  • Well, in my code the fist thing I do is to delete the "\\" at the beggining and the end of a path, convert the "/" to "\" and other similar checks. The code is working for me but if u want to improve it, yes, you can :D Thanks! – user3108594 Mar 26 '14 at 22:49
2

C:\files is not a File, it's a Directory.So you can try this:

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 you are not looking for a direct parent-child relationship you can try:

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

     Directory
    .GetDirectories(B.FullName, "*", SearchOption.AllDirectories)
    .Contains(A.FullName))
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

I needed to know if folder B was the same as OR was contained within folder A.

The following worked for me:

if (A.FullName.Contains(B.FullName))
{
// Path A is equal to or contained within path B. (B is a child of A)
}
Jay Brown
  • 139
  • 2
  • 13