C# - How can I convert an escaped string into a literal string? [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-10 17:31:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!