james raygan
james raygan

Reputation: 701

How to cut out a part of a path?

I want to cut out a part of a path but don't know how. To get the path, I use this code:

String path = System.IO.Path.GetDirectoryName(fullyQualifiedName);

(path = "Y:\Test\Project\bin\Debug")

Now I need the first part without "\bin\Debug".

How can I cut this part out of the current path?

Upvotes: 9

Views: 30076

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460098

You can use the Path class and a subsequent call of the Directory.GetParent method:

String dir = Path.GetDirectoryName(fullyQualifiedName);
string root = Directory.GetParent(dir).FullName;

Upvotes: 8

Maxim Zhukov
Maxim Zhukov

Reputation: 10140

If you know, that you don't need only "\bin\Debug" you could use replace:

path = path.Replace("\bin\Debug", "");

or

path = path.Remove(path.IndexOf("\bin\Debug"));

If you know, that you don't need everything, after second \ you could use this:

path = path.Remove(path.LastIndexOfAny(new char[] { '\\' }, path.LastIndexOf('\\') - 1));

and finally, you could Take so many parts, how many you want like this:

path = String.Join(@"\", path.Split('\\').Take(3));

or Skip so many parts, how many you need:

path = String.Join(@"\", path.Split('\\').Reverse().Skip(2).Reverse());

Upvotes: 18

andreea
andreea

Reputation: 86

You can obtain the path of the parent folder of your path like this:

path = Directory.GetParent(path);

In your case, you'd have to do it twice.

Upvotes: 1

ggcodes
ggcodes

Reputation: 2899

You can do it within only 3 lines.

String path= @"Y:\\Test\\Project\\bin\\Debug";
String[] extract = Regex.Split(path,"bin");  //split it in bin
String main = extract[0].TrimEnd('\\'); //extract[0] is Y:\\Test\\Project\\ ,so exclude \\ here
Console.WriteLine("Main Path: "+main);//get main path

Upvotes: 3

Related Questions