Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get root directory of a folder +1

Tags:

c#

.net

How can i get the root directory of a folder +1?

Example: Input: C:\Level1\Level2\level3 output should be:

Level1

If input is Level1 output should be Level1

if input is C:\ output should be empty string

Is there is a .Net function handles this?

Directory.GetDirectoryRoot will always returns C:\

like image 555
Maro Avatar asked Apr 17 '13 10:04

Maro


People also ask

How do I get to the root directory of a folder?

You can change to the root directory of the current drive with the “cd” command or switch to a root directory on another drive. The root directory is the top-most folder on the drive. For example, “C:\” is the root directory for the C: drive and “D:\” is the root directory for the D: drive.

Is C :\ a root directory?

For example, the root directory of the main partition on your computer is probably C:\. The root folder of your DVD or CD drive might be D:\.

How do I get to root directory in CMD?

Open Command Prompt in Windows 10 To change to the Root directory type cd\ and press Enter (Figure 10).


2 Answers

You can use the Path-class + Substring + Split to remove the root and get the top-folder.

// your directory:
string dir = @"C:\Level1\Level2\level3";     

// C:\  
string root = Path.GetPathRoot(dir); 

// Level1\Level2\level3:
string pathWithoutRoot = dir.Substring(root.Length);       

// Level1
string firstFolder = pathWithoutRoot.Split(Path.DirectorySeparatorChar).First(); 

Another way is using the DirectoryInfo class and it's Parent property:

DirectoryInfo directory = new DirectoryInfo(@"C:\Level1\Level2\level3");
string firstFolder = directory.Name;
while (directory.Parent != null && directory.Parent.Name != directory.Root.Name)
{
    firstFolder = directory.Parent.Name;
    directory = directory.Parent;
}

However, i would prefer the "lightweight" string methods.

like image 185
Tim Schmelter Avatar answered Oct 27 '22 00:10

Tim Schmelter


You could loop up using the directory info class using the following structure by adding the code section below into a method

string path = "C:\Level1\Level2\level3";
DirectoryInfo d = new DirectoryInfo(path);
while (d.Parent.FullName != Path.GetPathRoot(path))
{
    d = d.Parent;
}
return d.FullName;
like image 28
Patrick D'Souza Avatar answered Oct 26 '22 23:10

Patrick D'Souza