C# - 如何将转义字符串转换为文字字符串?

发布于 2024-11-05 06:38:05 字数 602 浏览 4 评论 0 原文

可能的重复:
我可以展开包含 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安静 2024-11-12 06:38:05

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.

疯到世界奔溃 2024-11-12 06:38:05

将转义值替换为 \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();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文