可能的重复:
我可以展开包含 C# 的字符串吗运行时的文字表达式
如何将从运行时文件读取的转义字符串(例如,转换
"Line1\nLine2"
为文字值):
Line1
Line2
令人惊讶的是,我找到了一个执行相反操作的示例 此处使用 CSharpCodeProvider(),这似乎是更困难的转换。为了做相反的事情,我似乎需要生成代码来定义一个类并在内存中编译它或执行一系列 .Replace() 调用,希望我不会错过任何转义序列。
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.
发布评论
评论(2)
CSharpCodeProvider 听起来肯定可以解决这个问题。但是,在使用它之前我会问两个问题:它是否必须完全是 C# 字符串文字语法,以及输入文件是否可信?
CSharpCodeProvider 显然提供了 C# 编译器的准确语法,但在我看来,某人通过此途径将一些代码注入到您的进程中相对容易。
Javascript 字符串文字语法与 C# 字符串文字语法相当接近,.NET 包含一个 JavaScriptSerializer 类可以解析此类字符串文字,而无需将其作为代码注入到正在运行的进程中。
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.
将转义值替换为
\n
Replace the escaped value by
\n