HTML-encodes a string and returns the encoded string. : HTML « Network « C# / C Sharp






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("&lt;");
                        break;
                    case '>':
                        sb.Append("&gt;");
                        break;
                    case '"':
                        sb.Append("&quot;");
                        break;
                    case '&':
                        sb.Append("&amp;");
                        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();
        }

    }
}

   
  








Related examples in the same category

1.Get Links From HTML
2.Parses the value information from any INPUT tag in an HTML string where the name="" attribute matched the tagID parameter
3.Html Utilities
4.Convert HTML To Text
5.Converts a FontUnit to a size for the HTML FONT tag
6.Strip HTML
7.Remove tags from a html string
8.Sanitize any potentially dangerous tags from the provided raw HTML input using a whitelist based approach
9.Get Type As Html
10.Strips all HTML tags from the specified string.
11.Removes the HTML whitespace.
12.Array To Html Breaked String
13.Show Html Page in String with Process