1

There is such method for CodeDom by @Hallgrim found here:

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();
        }
    }
}

Nowadays we need a Roslyn remake for .NET Core. Or should we manually replace symbols?

AsValeO
  • 2,859
  • 3
  • 27
  • 64

1 Answers1

4

You can create a SyntaxNode (LiteralExpressionSyntax) from the input string and than take the string representation of the created node:

public static string ToLiteral(this string input)
{
    return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(input)).ToFullString();
}
George Alexandria
  • 2,841
  • 2
  • 16
  • 24