views:

169

answers:

7
"C://test/test/test.png" -> blub

    blub = blub.Replace(@"/", @"\");

result = "C:\\\\test\\test\\test.png"

how does that make sense? It replaces a single / with two \

?

+1  A: 

Look up "escape characters".

Gareth Saul
The OP is already using @ properly.
Henk Holterman
+3  A: 

The \ character in C# is the escape character, so if you are going to use it as a \ character you need two - otherwise the next character gets treated specially (new line etc).

See What character escape sequences are available? (C#)

Moo
+2  A: 

The character \ is a special character, which changes the meaning of the character after it in string literals. So when you refer to \ itself, it needs to be escaped: \\.

Péter Török
+7  A: 

No, it doesn't.

What you're seeing is the properly formatted string according to C# rules, and since the output you're seeing is shown as though you haven't prefixed it with the @ character, every backslash is doubled up, because that's what you would have to write if you wanted that string in the first place.

Create a new console app and write the result to the console, and you'll see that the string looks like you wanted it to.

So this is just an artifact of how you look at the string (I assume the debugger).

Lasse V. Karlsen
A: 

You should think twice before saying something like that....

The string.Replace function is basic functionality that has been around for a long time.... Whenever you find you have a problem with something like that, it's probably not the function that is broken, but your understanding or use of it.

Quagmire
+9  A: 

It's actually working:

string blub = "C://test/test/test.png";
string blub2 = blub.Replace(@"/", @"\");

Console.WriteLine(blub);
Console.WriteLine(blub2);

Output:

C://test/test/test.png
C:\\test\test\test.png

BUT viewing the string in the debugger does show the effect you describe (and is how you would write the string literal in code without the @).

I've noticed this before but never found out why the debugger chooses this formatting.

Paolo
Because if the debugger didn't choose this formatting, it'd be giving ambiguous output all the time. (How would the debugger output strings that contain quotes if it didn't use the escape characters?).
Dan Puzey
I guess that makes sense then :)
Paolo
Thanks for the tip with the debugger, that helped me understand it.
Blub
+1  A: 

Its done what it should. "\\" is the same as @"\"

"\" is an escape character. Without the verbatim indicator "@" before a string a single \ is shown as "\\"

ChrisBD