2

Possible Duplicate:
Can I convert a C# string value to an escaped string literal

How I can show the contents of a string in 'pure mode',including \r,\n,\t etc.. equivalent to .toSource() method of javascript

For example:

JavaScript:

var str = "foo\nbaa\ttest"; 
console.log(str.toSource());

Output:

(new String("foo\nbaa\ttest"))

it is possible do this in C#? Thanks in advance!

0

3 Answers 3

3

See the answer to Can I convert a C# string value to an escaped string literal . He wrote this extension method that does exactly what you're wanting:

static string ToLiteral(string input)
{
    var writer = new StringWriter();
    CSharpCodeProvider provider = new CSharpCodeProvider();
    provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
    return writer.GetStringBuilder().ToString();
}
1
Regex.Escape("foo\nbaa\ttest")
1
  • @Ahmad I saw, but you had a more complete answer. Sep 29, 2011 at 21:56
0

Looking at the general problem - reconstructing some source code - there is no language option on C# that would let you do it automagically.

However (this is theory on my part) you should be able to use expressions to get to the IL equivalent (using the Reflection.Emit or Mono.Cecil libraries perhaps). You could I suspect then use the libraries from the ILSpy project to reconstruct the C#.

Not the answer you're looking for? Browse other questions tagged or ask your own question.