Thursday, 10 October 2013

Remove HTML White Space in ASP.NET C#

Hello Friend I am writing here how to remove white space from HTML page

Remove the HTML white space at runtime in ASP.NET will reduce the HTML page size so the page will be load very quickly. This method is for SEO purposes also.

Add the code below to any ASPX.CS page or Master page, then browse the page to see the magic.

using System.Text.RegularExpressions;


        private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);
        private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);

        protected override void Render(HtmlTextWriter writer)
        {
            using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
            {
                base.Render(htmlwriter);
                string html = htmlwriter.InnerWriter.ToString();

                html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
                html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

                writer.Write(html.Trim());
            }
        }



0 comments:

Post a Comment