Reputation: 291
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.
Upvotes: 2
Views: 425
Reputation: 7817
in this string the \\
are escapes for \
:
var path = "d:\\project\\Bloomberg\\trunk\\UI.Demo\\";
so this actually says:
@"d:\project\Bloomberg\trunk\UI.Demo\"
So when you replace \\
with \
you're not replacing anything. double slashed would look like \\\\
in normal strings. Which you did correctly in your replace method.
Upvotes: 1
Reputation: 39610
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\";
Upvotes: 10
Reputation: 3979
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/";
Upvotes: 2
Reputation: 24150
Change:
var path = "d:\\project\\Bloomberg\\trunk\\UI.Demo\\";
to:
var path = @"d:\\project\\Bloomberg\\trunk\\UI.Demo\\";
and you will be good. Remember that \\
means \
in normal strings, so if you want actual double backslashes you need to use \\\\
or simply prefix your string with @ - just like in your calls to Replace.
Secondly, as it is you probably don't need to call Replace in your particular situation since those \\
you see actually are single backslashes since your string is not prefixed with @, and the escape sequences are evaluated.
Upvotes: 1