问题
Possible Duplicate:
Can I expand a string that contains C# literal expressions at runtime
How can I convert an escaped string read from a file at runtime, e.g.
"Line1\nLine2"
into its literal value:
Line1
Line2
Amazingly I have found an example to do the opposite here using CSharpCodeProvider(), which seems like it would be the more difficult conversion. In order to do the opposite it appears I need to generate code to define a class and compile it in memory or execute a series of .Replace() calls, hoping I don't miss any escape sequences.
回答1:
CSharpCodeProvider sounds like it certainly can do the trick here. However, I would ask 2 questions before using that: is it required to be exactly C# string literal syntax, and is the input file trusted?
CSharpCodeProvider obviously provides exactly the syntax of the C# compiler, but it seems to me like it'd be relatively easy for someone to inject some code into your process via this route.
The Javascript string literal syntax is fairly close to the C# string literal syntax, and .NET includes a JavaScriptSerializer class which can parse such string literals without injecting it as code into the running process.
回答2:
Replace the escaped value by \n
static void Main(string[] args)
{
var test = "Line1\\nLine2";
// Line1\nLine2
Console.WriteLine(test);
// Line1
// Line2
Console.WriteLine(test.Replace("\\n", Environment.NewLine));
Console.ReadKey();
}
来源:https://stackoverflow.com/questions/5889057/c-sharp-how-can-i-convert-an-escaped-string-into-a-literal-string