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

Sjors Miltenburg picture Sjors Miltenburg · Aug 19, 2010 · Viewed 13.5k times · Source

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.

Answer

Steve Dunn picture Steve Dunn · Oct 10, 2011

In response to the first part of the question: "Is dir1 a sub-directory of dir2?", this code should work:

public bool IsSubfolder(string parentPath, string childPath)
{
    var parentUri = new Uri(parentPath);
    var childUri = new DirectoryInfo(childPath).Parent;
    while (childUri != null)
    {
        if(new Uri(childUri.FullName) == parentUri)
        {
            return true;
        }
        childUri = childUri.Parent;
    }
    return false;
}

The URIs (on Windows at least, might be different on Mono/Linux) are case-insensitive. If case sensitivity is important, use the Compare method on Uri instead.