Search code examples
c#stringescapingdouble-quotes

Escape double quotes in a C# string


I'm trying to escape \ and " in my string like this:

text.Replace("\\", "\\\\").Replace("\"", "\\\"");

But the result for text,

arash "moeen"

turns out as

arash \\\"moeen\\\"

How can I fix this?


Solution

  • Just use @ for verbatim literal strings.

    text.Replace(@"this", @"that");
    

    Example:

    text.Replace(@"\", @"\\").Replace(@"""", @"\""");