Reputation: 294
I would like to check the path.
For example, I want a method that has functionality below.
Two path string is "C:\Document\test", "C:Document\test2".
And If "C:\Document\test" is compared with "C:Document\test2"
then the result is expected false because "C:\Document\test"
is not included in "C:Document\test2".
Another example is
Two path string is "C:\Document\test", "C:Document\test\test2".
If "C:\Document\test"
is compared with "C:Document\test\test2"
then the resulut is expected true because "C:\Document\test"
is included in "C:Document\test\test2".
Is there a method that has functionality the above in C#?
Thanks for reading.
Upvotes: 0
Views: 146
Reputation: 18155
You could use string comparison for the purpose. For example,
public static bool ComparePath(string path1,string path2)
{
return NormalizePath(path2).Contains(NormalizePath(path1));
}
public static string NormalizePath(string path)
{
if(path.Trim().Last().Equals(Path.DirectorySeparatorChar))
return path.Trim().ToLower();
return $"{path.Trim()}{Path.DirectorySeparatorChar}".ToLower();
}
You need to include the DirectorySeparatorChar to mark end of path.
Example,
ComparePath(@"C:\Document\test",@"C:\Document\test\2"); // True
ComparePath(@"C:\Document\test",@"C:\Document\test2"); // False
Upvotes: 1
Reputation: 185
I think the PathUtil.IsDescendant(String, String)
Method is exactly what you Need. You find the documentation here.
var res = PathUtil.IsDescendant("C:\\Test\\Test1\\", "C:\\Test\\Test1\\Test2.txt");
res = PathUtil.IsDescendant("C:\\Test\\Test", "C:\\Test\\Test2");
The first will return true
and the second will return false
Upvotes: 1