hi, i have a string like this:

string a = "My Documents\\Results\\" + "6" + "\\default.jpg";

i want to operate on it so that it become like this instead:

"My Documents\\Results\\" + "6" + "\\"

how do i do it. i have tried string.splitend and it does not work.
any advice is appreciated.thanks in advance

Re: Visual C# General string operation

Jeremy Filburn

Code Snippet

string a = "My Documents\\Results\\" + "6" + "\\default.jpg";

a = a.Remove(a.LastIndexOf("\\") + 1);


Re: Visual C# General string operation

Martin Platt

Console.Write(a.substring(0, a.IndexOf("\\")));

Re: Visual C# General string operation


string resultsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Results");

string a = Path.Combine(Path.Combine(resultsDir, "6"), "default.jpg");

// to get directory from filename:
string aDir = Path.GetDirectoryName(a);

resultsDir should then be "...My Documents\Results"
a shoud be "...My Documents\6\default.jpg"
aDir should be "...My Documents\6\"

I like to use Path.Combine instead of string concatenation to avoid problems with extra/missing slashes, but you don't have to; you can use your existing code if you want and just use the bolded line (Path.GetDirectoryName).

If you want to use IndexOf, do almost like Martin's solution except with LastIndexOf.