Thursday, November 10, 2011

Converting string to literal

Recently I need it to solve the issue how to convert string to literal. My demands were simple. I get string value from somewhere (SharePoint list) then I needed to convert this string to literal. It is really simple to do it by @ sign, but this doesn't work when you obtain value from some source.
For better understanding here is example:
This works fine:
        string sValue = @"This is \nexample."; 
and this doesn't :
        static class MyClass
        {
            public static string myString = "This is \nexample.";   
        }


        static void Main(string[] args)
        {
            string myString = @MyClass.myString;
            Console.WriteLine(myString);
            Console.WriteLine("Press Enter to continue...");
            Console.ReadLine();
        }


If you don't know what @ is for, lets have look here.

After all searching and trying I finally found solution on stockOverflow:
Here is the link and here is the code snippet:

static string ToLiteral(string input)
    {
        var writer = new StringWriter();
        CSharpCodeProvider provider = new CSharpCodeProvider();
        provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
        return writer.GetStringBuilder().ToString();
    }
I have to thank Hallgrim for this code 'cause it really saved me :)

No comments:

Post a Comment