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?

1

2 Answers 2

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

4 Comments

I updated my question, I'm still getting the encoded value even though i encode and decode, please see my question.
@AbuHamzah See my update, but for this case, you just need to decode it.
Thanks and I have another string with &amp;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?
&amp;amp; is & encoded twice. If you decoded it twice, you would probably get the expected result.
1

tagText = SecurityElement.Escape(tagText);

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

or

 System.Net.WebUtility.HtmlDecode(textContent);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.