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
  • 165,109
  • 17
  • 150
  • 199
jeroenh
  • 25,492
  • 9
  • 70
  • 102

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,234
  • 1
  • 13
  • 22