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

后端 未结 16 846
时光取名叫无心
时光取名叫无心 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:22

    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 might help people who end up here from Google.

提交回复
热议问题