c# replace \" characters

Tim Shults picture Tim Shults · Jan 12, 2011 · Viewed 204.9k times · Source

I am sent an XML string that I'm trying to parse via an XmlReader and I'm trying to strip out the \" characters.

I've tried

.Replace(@"\", "")
.Replace("\\''", "''")
.Replace("\\''", "\"")

plus several other ways.

Any ideas?

Answer

Jon Skeet picture Jon Skeet · Jan 12, 2011

Were you trying it like this:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)