Question

EDIT - Modified based on the answer:

okay here is what I modified based on the answer:

here is the string.

"November is Fruit's Fresh."    

here is what I'm doing:

    static string EscapeCharacters(string txt)
    {
        string encodedTxt = HttpUtility.HtmlEncode(txt);
        return HttpUtility.HtmlDecode(encodedTxt);
    }

    string _decodedTxt = EscapeCharacters("November is Fruit's Fresh.");

when it returns I'm still getting the same text November is Fruit's Fresh.

END EDIT

I tried using HttpUtility.HtmlDecode from System.Web and also tried using SecurityElement.Escape but it does not escapes anything correctly.

so I end-up writing my own replace method something like this:

    static string EscapeXMLCharacters(string txt)
    {
        string _txt = txt.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace("&apos;", "'").Replace("&#38;", "&").Replace("&#60;", "<").Replace("&#62;", ">").Replace("&#34;", "\\").Replace("&#39;", "'");
        return _txt;
    }

it does work in my situation but its hard to cover everything and in my situation I have some European characters like í``(&#237;) or é (&#233;)

Is there a utility method built-in .Net that take cares of any special characters?

Was it helpful?

Solution

You can use HtmlEncode to encode the string and then you can use HtmlDecode to return the original value:

string x = "éí&";
string encoded = System.Web.HttpUtility.HtmlEncode(x);
Console.WriteLine(encoded);  //&#233;&#237;&amp;

string decoded = System.Web.HttpUtility.HtmlDecode(encoded);
Console.WriteLine(decoded);  //éí&

With your update, you just need to decode the string:

String decoded = System.Web.HttpUtility.HtmlDecode("November is Fruit&#39;s Fresh.");
Console.WriteLine(decoded);   //November is Fruit's Fresh.

OTHER TIPS

tagText = SecurityElement.Escape(tagText);

http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape.aspx

or

 System.Net.WebUtility.HtmlDecode(textContent);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top