Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, Replace "\\" to "\"

Tags:

c#

replace

I have a string:

var path = "d:\\project\\Bloomberg\\trunk\\UI.Demo\\";

I am trying to replace \\ to \.

I've tried this:

path = path.Replace("\\\\", "\\");
path = path.Replace(@"\\", @"\");

None of those replaces the double backslashes with single backslash.

like image 331
Ilya Shpakovsky Avatar asked Feb 13 '26 05:02

Ilya Shpakovsky


2 Answers

The path doesn't contain any double backslashes. "blah\\blah" is actually blah\blah.

In normal string literals (those not starting with an @), you need to escape some characters by putting a backslash (\) in front of them. One of those characters is the backslash itself, so if you want to put one backslash into a string, you escape it with another backslash, which is why path contains all those double backslashes. At runtime, those will be single backslashes.

See here for the available escape sequences: C# FAQ: Escpape Sequences

Verbatim Strings (thos starting with an @) on the other hand, don't require escaping for most of those characters. So @"\"actually is \. The only characters you need to escape in a verbatim string are quotes. You do this by just typing a double quote. So @"""" is actually ".

So if you wanted to put d:\project\Bloomberg\trunk\UI.Demo\ into a string, you have two possibilities.

Normal String literal (note that \ is escaped):

var path = "d:\\project\\Bloomberg\\trunk\\UI.Demo\\";

or verbatim string literal (no need to escape \):

var path = @"d:\project\Bloomberg\trunk\UI.Demo\";
like image 66
Botz3000 Avatar answered Feb 15 '26 12:02

Botz3000


you do not forget to put @? front of your chain said ?

var path = @"d:\\project\\Bloomberg\\trunk\\UI.Demo\\"; 

But that -> @"d:\project\Bloomberg\trunk\UI.Demo\";
is egal -> "d:/project/Bloomberg/trunk/UI.Demo/";

like image 45
Mehdi Bugnard Avatar answered Feb 15 '26 11:02

Mehdi Bugnard