HttpUtility.HtmlEncode Method & HttpUtility.HtmlDecode Method (System.Web)

I recently got a chance to resolve one of the QA feedback regarding encryption/decryption with special characters where QA reported an exception when data entered with special characters.

Since the encryption/decryption is happening at the server side and is communicating the data back to the client via xml so some special characters have a special meaning in xml e.g < > ” ‘ . They could mess up the xml format if not properly escaped so when data is decrypted and sent to the client within an xml it needs to be escaped (encode) before appending it within the xml data sent back to the client

e.g:
< should be escaped (encoded) as &lt; 
> should be escaped as &gt;
' should be escaped as &#39;
" should be escaped as &quot;

And fortunately, we have a builtin function in .net 4 to help use with that -HttpUtility.HtmlEncode. 

Once the client got the xml, we want to unescaped (decode) the string back to human readable string and fortunuately we have the builtin function within .net 4 to help us with that HttpUtility.HtmlDecode

Sample console app to demonstrate:

using System;
using System.Web;
using System.IO;

class MyNewClass
{
    public static void Main()
    {
        Console.WriteLine("Enter a string having '&', '<', '>' or '\"' in it: ");
        string myString = Console.ReadLine();

        // Encode the string.
        string myEncodedString = HttpUtility.HtmlEncode(myString);

        Console.WriteLine($"HTML Encoded string is: {myEncodedString}");
        StringWriter myWriter = new StringWriter();

        // Decode the encoded string.
        HttpUtility.HtmlDecode(myEncodedString, myWriter);

        string myDecodedString = myWriter.ToString();
        Console.Write($"Decoded string of the above encoded string is: {myDecodedString}");
    }
}