Question

I have an issue when converting a string from stringbuilder to string. The issue is similar to this issue but slightly different:

This is my code simplified:

StringBuilder sb = new StringBuilder();
sb.Append("\"");
sb.Append("Hello World");
sb.Append("\"");

string test = sb.ToString();

Now in the debugger the sb value is:

"Hello World"

In the debugger the test string value is changed to:

\"Hello World\"

When returning the test string value back to the browser the velue is STILL escaped:

\"Hello World\"

I have tried using the string replace:

test = test.Replace("\"", "");

no luck, I tried appending the ASCII character instead of \" and I have also tried a different append

sb.Append('"');

All these with no luck. Can somebody maybe point me in the right direction of why I'm still getting the escape character and how to get rid of it.

Thanks and appreciate any input.

Was it helpful?

Solution

Ok it seems that in WCF the stringBuilder automatically adds escape quotes. This means you can not get away from that. Also I was going about this all wrong. I was trying to return a string where I was supposed to return a serialised JSON object.

OTHER TIPS

I'm not seeing the behavior you describe. Escaping double quotes with the backslash should work. The following snippet of code

        var sb = new StringBuilder();
        sb.Append("Ed says, ");
        sb.Append("\"");
        sb.Append("Hello");
        sb.Append("\"");
        Console.WriteLine(sb.ToString());
        foreach (char c in sb.ToString()) Console.Write(c + "-");
        Console.ReadKey();

produces

Ed says, "Hello"
E-d- -s-a-y-s-,- -"-H-e-l-l-o-"-

If you are getting actual backslash characters in your final display of the string, that may be getting added by something after the StringBuilder and ToString code.

You can use a verbatim string literal "@" before the string, then enter the quotes twice. This removes the use to use escapes in the string sequence :)

StringBuilder sb = new StringBuilder();
sb.Append(@"""");
sb.Append("Hello World");
sb.Append(@"""");

string test = sb.ToString();

This question and answer thread kept on coming up when searching for the solution. The confusion, for me, was that the Debugger escaping looks exactly the same as the JSON serializer behaviour that was being applied later when I returned the string to a client. So the code at the top of the thread (and my code) worked correctly.

Once I realised that, I converted the piece of code I was working on return an array (string[] in this case) and store that rather than the original string object. Later the JSONResult serializer then dealt with converting the array correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top