using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
//将C#字符串值转换为转义的字符串文字
public static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions { IndentString = "\t" });
return writer.ToString().Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
}
}
}
var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));
Hello
World!
"\tHello\r\n\tWorld!"