Shuo
Shuo

Reputation: 4849

C# Path operations

I need to get "first_level" and "second_level\third_level" from the original path "first_level\second_level\third_level", something that splits the path into two part by the first separator. Is there any C# method in .net library that does that?

Upvotes: 1

Views: 459

Answers (2)

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

Use the Split overload that takes a count for the maximum number of substrings to return:

string input = @"first_level\second_level\third_level";
string[] result = input.Split(new[] { '\\' }, 2);
foreach (string s in result)
    Console.WriteLine(s);

// result[0] = "first_level"
// result[1] = "second_level\third_level"

Upvotes: 3

Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

string myPath = @"first_level\second_level\third_level";

string[] levels = myPath.Split('\\');

and

    level[0] will be equal to first_level
    level[2] will be equal to second_level
    level[3] will be equal to third_level

you asking this?

Upvotes: 3

Related Questions