How to get the first directory name in a relative path, given that they can be different accepted directory separators?
For example:
foo\bar\abc.txt -> foo
bar/foo/foobar -> bar
Seems like you could just use the string.Split() method on the string, then grab the first element.
example (untested):
string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";
string[] items = str.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "foo"
items = str2.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "bar"
Works with both forward and back slash
static string GetRootFolder(string path)
{
while (true)
{
string temp = Path.GetDirectoryName(path);
if (String.IsNullOrEmpty(temp))
break;
path = temp;
}
return path;
}
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