Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut out a part of a path?

Tags:

c#

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?

like image 600
james raygan Avatar asked Jul 22 '13 08:07

james raygan


3 Answers

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());
like image 170
Maxim Zhukov Avatar answered Sep 22 '22 01:09

Maxim Zhukov


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;
like image 33
Tim Schmelter Avatar answered Sep 21 '22 01:09

Tim Schmelter


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
like image 45
ggcodes Avatar answered Sep 22 '22 01:09

ggcodes