0

Given this sample code:

var s = "abc\r\ndef";
foreach (var c in s)
{
    Console.WriteLine($"Current char: {c}");
}

Of course, the '\r' and '\n' characters, are written as whitespace and an actual newline, respectively. What I want to achieve is to write '\r', '\n' instead.

What's the easiest way to convert a character to it's (C#) 'escaped representation'? Should I look at Roslyn for this, or is there a simple conversion function available?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
jeroenh
  • 26,362
  • 10
  • 73
  • 104

1 Answers1

0

This should answer your question, you can see it here: Can I convert a C# string value to an escaped string literal

private static string ToLiteral(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return writer.ToString();
        }
    }
}
Community
  • 1
  • 1
Felix Av
  • 1,254
  • 1
  • 14
  • 22