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();
}
Sign up to request clarification or add additional context in comments.

Comments

1
Regex.Escape("foo\nbaa\ttest")

1 Comment

@Ahmad I saw, but you had a more complete answer.
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#.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.