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!

Community
  • 1
  • 1
The Mask
  • 17,007
  • 37
  • 111
  • 185

3 Answers3

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();
}
Community
  • 1
  • 1
CassOnMars
  • 6,153
  • 2
  • 32
  • 47
1
Regex.Escape("foo\nbaa\ttest")
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
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#.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216