Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

directory

I have 2 strings - dir1 and dir2, and I need to check if one is sub-directory 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 sub-directories, bet returns true. There must be a better way.

like image 435
andree Avatar asked Apr 11 '11 06:04

andree


People also ask

Which directory contain a subdirectory in it?

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 is folder related to subdirectory?

A subdirectory is a type of website hierarchy under a root domain that uses folders to organize content on a website. A subdirectory is the same as a subfolder and the names can be used interchangeably.

What is subdirectory in operating system?

Definition of subdirectory : an organizational directory on a computer that is located within another directory : subfolder The file you are looking for should have an extension of .EXE.


1 Answers

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; } 
like image 198
BrokenGlass Avatar answered Sep 22 '22 01:09

BrokenGlass