Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 760
Sjors Miltenburg Avatar asked Aug 19 '10 20:08

Sjors Miltenburg


People also ask

Is directory a subdirectory?

In a computer file system, a subdirectory is a directory that is contained another directory, called a parent directory. A parent directory may have multiple subdirectories.

How do I find a subdirectory in Windows?

Open Windows Explorer. Select Organize / Folder and Search options. Select the Search Tab. In the How to search section, select the Include subfolders in search results when searching in file folders option.

What are directories and subdirectories?

Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a subdirectory.

How many subdirectories can a directory have?

Answer. What is the maximum number of subdirectories that a single directory might contain? Subdirectories might be limited by the number of available inodes and maxdirsize setting. There is a limit of 99,998 directories per sub-directory.


1 Answers

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.

like image 152
Steve Dunn Avatar answered Sep 20 '22 06:09

Steve Dunn