C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part A: The HtmlEncode method is designed to receive a string that contains HTML markup characters such as > and <.
Part B: HtmlDecode, meanwhile, is designed to reverse those changes. It changes encoded characters back to actual HTML.
C# program that uses HtmlEncode and HtmlDecode
using System;
using System.Net;
class Program
{
static void Main()
{
// Part A: encode this string.
string encoded = WebUtility.HtmlEncode("<b>Hello 'friend'</b>");
// Part B: reverse the change.
string decoded = WebUtility.HtmlDecode(encoded);
// Print results.
Console.WriteLine("ENCODED: {0}", encoded);
Console.WriteLine("DECODED: {0}", decoded);
}
}
Output
ENCODED: <b>Hello 'friend'</b>
DECODED: <b>Hello 'friend'</b>
Here: We see 3 methods. The first 2 return an encoded or decoded string, and the HtmlTextWriter uses a method called WriteEncodedText.
Note: This may be more efficient, as it could avoid a string copy. I tested these methods with breakpoints.
HtmlTextWriterC# program that uses ASPX code-behind, encodes HTML
using System;
using System.IO;
using System.Web;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This could mess up HTML.
string text = "you & me > them"; // 1
// Replace > with >
string htmlEncoded = Server.HtmlEncode(text); // 2
// Now has the > again.
string original = Server.HtmlDecode(htmlEncoded); // 3
// This is how you can access the Server in any class.
string alsoEncoded = HttpContext.Current.Server.HtmlEncode(text); // 4
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
// Write a DIV with encoded text.
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.WriteEncodedText(text);
writer.RenderEndTag();
}
string html = stringWriter.ToString(); // 5
}
}
Notes:
1: Before encoding has occurred.
String: you & me > them
2: The string is encoded for HTML.
String: you & me > them
3: String is converted back from HTML.
String: you & me > them
4: The string is encoded for HTML again.
String: you & me > them
5: The HTML string is written into a DIV.
Text: <div>you & me > them</div>