How to effectively check 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:

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

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

But that will not work. For example, if I write "C: \ files" and "C: \ files baaa", the code considers that "C: \ files baaa" is a child of "C: \ files", when it is not, it is only C: . The problem is very difficult when I try with long paths, with the number of children.

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

What can I do?

Thank!

+4
2

:

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 ... */ }
+4

C:\files File, a 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))
+2

Source: https://habr.com/ru/post/1533599/


All Articles