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!
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 ... */ }
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With