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:\
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.
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:\.
Open Command Prompt in Windows 10 To change to the Root directory type cd\ and press Enter (Figure 10).
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.
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;
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