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

后端 未结 16 1000
时光取名叫无心
时光取名叫无心 2020-11-22 07:51

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

16条回答
  •  青春惊慌失措
    2020-11-22 08:09

    I found this:

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

    This code:

    var input = "\tHello\r\n\tWorld!";
    Console.WriteLine(input);
    Console.WriteLine(ToLiteral(input));
    

    Produces:

        Hello
        World!
    "\tHello\r\n\tWorld!"
    

提交回复
热议问题