Monday 21 November 2011

Output a String With Escape Characters

Not something that is often required, but something that popped up today - how to get the literal output from a String object in C# including the escape characters.

So let's take a String variable declared like this:

string str = @"c:\temp";

The literal string is c:\temp, but what if we wanted the underlying escaped string which would look something like this:

"c:\\temp"

Not so easy.  Fortunately, Google being the fount of all knowledge these days, I put it to work in finding some help and unearthed a neat example from Stack Overflow using an Extension Method:

internal static class ExtensionFunctions
{
    internal static String ToLiteral(this String input)
    {
        var writer = new StringWriter();
        CSharpCodeProvider provider = new CSharpCodeProvider();
        provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
        return writer.ToString();
    }
}

To use it simply type str.ToLiteral(); and it will return the string complete with the escape sequence intact.

No comments:

Post a Comment