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.
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.
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.
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.
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.
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 URI
s (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With