HTML-encodes a string and returns the encoded string.
using System.Globalization; using System.Linq; using System.Text; namespace jQueryBuddy.Utilities { public static class StringExtensions { /// <summary> /// HTML-encodes a string and returns the encoded string. /// </summary> /// <param name="html">The html string to encode. </param> /// <returns>The HTML-encoded text.</returns> public static string EncodeHtml(this string html) { if (html == null) return null; var sb = new StringBuilder(html.Length); var len = html.Length; for (var i = 0; i < len; i++) { switch (html[i]) { case '<': sb.Append("<"); break; case '>': sb.Append(">"); break; case '"': sb.Append("""); break; case '&': sb.Append("&"); break; default: if (html[i] > 159) { // decimal numeric entity sb.Append("&#"); sb.Append(((int)html[i]).ToString(CultureInfo.InvariantCulture)); sb.Append(";"); } else sb.Append(html[i]); break; } } return sb.ToString(); } } }