4

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.

Community
  • 1
  • 1
Brandon
  • 702
  • 7
  • 15
  • I think he means `"Line1\\nLine2"` into `"Line1\nLine2"`. – Ry- May 04 '11 at 19:51
  • 1
    What is your goal? If you include a a statement like `string s = "Line\nLine2";` in your code, and then compile and run it, at runtime in memory, the variable s contains what you want to create. – Cheeso May 04 '11 at 19:51

2 Answers2

2

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.

Ken
  • 486
  • 3
  • 11
  • I am working with Regular Expressions, copying them from source to test them, then pasting them back in with modifications. Because they are regular expressions, they need to be exact translations back and forth. This is being used for a dirty little tool to simplify this process. – Brandon May 04 '11 at 21:09
  • This is the correct answer. It is not a duplicate and the CodeDom answer is a tad absurd for the reasons Ken gives. – Seth Jul 27 '15 at 22:52
0

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();
}
BrunoLM
  • 97,872
  • 84
  • 296
  • 452