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?
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());
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;
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
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