andree andree - 23 days ago 6
C# Question

Given full path, check if path is subdirectory of some other path, or otherwise

I have 2 strings - dir1 and dir2, and I need to check if one is subdirectory for other. I tried to go with Contains method:

dir1.contains(dir2);


, but that also returns true, if directories have similar names, for example - c:\abc and c:\abc1 are not subdirectories, bet returns true. There must be a better way.

Answer Source
DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = di2.Parent.FullName == di1.FullName;

Or in a loop to allow for nested sub-directories, i.e. C:\foo\bar\baz is a sub directory of C:\foo :

DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = false;
while (di2.Parent != null)
{
    if (di2.Parent.FullName == di1.FullName)
    {
        isParent = true;
        break;
    }
    else di2 = di2.Parent;
}