Get root directory of a folder +1
.net, c#
Solution
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.
Problem
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:\`