Search code examples
c#stringescapingroslyn

Can I convert a C# string value to an escaped string literal?


In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.

If this code:

Console.WriteLine(someString);

produces:

Hello
World!

I want this code:

Console.WriteLine(ToLiteral(someString));

to produce:

\tHello\r\n\tWorld!\r\n

Solution

  • There's a method for this in Roslyn's Microsoft.CodeAnalysis.CSharp package on NuGet:

    private static string ToLiteral(string valueTextForCompiler)
    {
        return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
    }
    

    Obviously, this didn't exist at the time of the original question, but it might help people who end up here from Google Search.