4

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?

Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

2 Answers2

2

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.
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • I updated my question, I'm still getting the encoded value even though i encode and decode, please see my question. – Nick Kahn Nov 07 '13 at 15:56
  • @AbuHamzah See my update, but for this case, you just need to decode it. – John Koerner Nov 07 '13 at 15:58
  • Thanks and I have another string with `&amp;` is that even valid? this is driving me crazy and it should not be that difficult but looks like the data i am getting is bad? – Nick Kahn Nov 07 '13 at 16:04
  • 1
    `&amp;` is `&` encoded twice. If you decoded it twice, you would probably get the expected result. – John Koerner Nov 07 '13 at 16:13
1

tagText = SecurityElement.Escape(tagText);

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

or

 System.Net.WebUtility.HtmlDecode(textContent);
Mohamed.Abdo
  • 2,054
  • 1
  • 19
  • 12