I have a string which is a file path:
string test = "C:\Users\Folder\File.txt";
what I wanted to do was to replace everything after the last backslash, i.e the filename by test.
I’m trying to do it like so:
string test = "C:\\Users\\Folder\\File.txt";
Regex rx = new Regex(@"\\S*(?!.*\\)");
string result = rx.Replace(test, "\\test.txt");
But this gives me: C:\Users\Folder\test.txtFile.txt" instead of C:\Users\Folder\test.txt", what am I doing wrong?
>Solution :
I wouldn’t do that with Regex but Path really:
string test = "C:\\Users\\Folder\\File.txt";
Regex rx = new Regex(@"\\S*(?!.*\\).*");
string result = rx.Replace(test, "\\test.txt");
Console.WriteLine(result);
var betterWay = Path.Combine(Path.GetDirectoryName(test), "test.txt");
Console.WriteLine(betterWay);