Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check effectively if one path is a child of another path in C#?

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!

like image 612
user3108594 Avatar asked Mar 26 '14 19:03

user3108594


2 Answers

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 ... */ }
like image 146
Dmitry Avatar answered Nov 15 '22 05:11

Dmitry


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))
like image 20
Selman Genç Avatar answered Nov 15 '22 06:11

Selman Genç