How to check if directory 1 is a subdirectory of dir2 and vice versa

Viewed 15548

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-ready function for this. I thought it would be in there somewhere.

Do you guys have an idea where to find this?

I tried writing a check myself, but it's more complicated than I had anticipated when I started.

11 Answers
public static bool IsSubfolder(DirectoryInfo parentPath, DirectoryInfo childPath)
{
return parentPath.FullName.StartsWith(childPath.FullName+Path.DirectorySeparatorChar);
}

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, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
    dirPath = dirPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
    if (!dirPath.EndsWith(Path.DirectorySeparatorChar))
    {
      dirPath += Path.DirectorySeparatorChar;
    }
  
    baseDirPath = baseDirPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
    if (!baseDirPath.EndsWith(Path.DirectorySeparatorChar))
    {
      baseDirPath += Path.DirectorySeparatorChar;
    }

    string dirPathUri = new Uri(dirPath).LocalPath;
    string baseDirUri = new Uri(baseDirPath).LocalPath;

    return dirPathUri.Contains(baseDirUri, comparisonType);
}
Related