Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Get first directory name of a relative path

Tags:

string

c#

.net

path

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
like image 507
Louis Rhys Avatar asked Oct 27 '11 03:10

Louis Rhys


2 Answers

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"
like image 105
jb. Avatar answered Sep 19 '22 13:09

jb.


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;
}
like image 32
Muhammad Hasan Khan Avatar answered Sep 20 '22 13:09

Muhammad Hasan Khan