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.
If you have two path then look at this:
Normalize directory names in C#
http://filedirectorypath.codeplex.com/ (I don't know the quality of it)
And use this:
Otherwise, if you want to know whether a directory exists as a subdirectory in a path take a look on:
Came in
.Net 4.0
. Example:Does
path
contain a directory starting withConsole
:You can use Path.GetDirectoryName Method to get parent directory. It works for directories too.
See original answer here: https://stackoverflow.com/a/31941159/134761
\
and/
folder delimiters..\
in pathc:\foobar
not a subpath ofc:\foo
)Code:
Test cases (NUnit):
Update 2015-08-18: Fix bug matching on partial folder names. Add test cases.
Update 2016-01-29: Link to original question https://stackoverflow.com/a/31941159/134761
You can compare directory2 to directory1's
Parent property
when using a DirectoryInfo in both cases.DirectoryInfo has a property Parent which is also a DirectoryInfo type. You can use that to to determine if your directory is a subdirectory of a parent directory.