What is an easy way to check if directory 1 is a subdirectory of directory 2 and vice versa?
I checked the Path and DirectoryInfo helperclasses but found no system-r
With help from the great test cases written in angularsen's answer, I wrote the following simpler extension method on .NET Core 3.1 for Windows:
public static bool IsSubPathOf(this string dirPath, string baseDirPath)
{
dirPath = dirPath.Replace('/', '\\');
if (!dirPath.EndsWith('\\'))
{
dirPath += '\\';
}
baseDirPath = baseDirPath.Replace('/', '\\');
if (!baseDirPath.EndsWith('\\'))
{
baseDirPath += '\\';
}
var dirPathUri = new Uri(dirPath).LocalPath;
var baseDirUri = new Uri(baseDirPath).LocalPath;
return dirPathUri.Contains(baseDirUri, StringComparison.OrdinalIgnoreCase);
}