本文实例讲述了C#实现压缩html代码的方法,分享给大家供大家参考之用。具体方法如下:
主要代码如下:
/// <summary> /// 压缩html代码 /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { System.IO.StringWriter html = new System.IO.StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(html); base.Render(tw); string outhtml = html.ToString(); outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "\\n+\\s+", string.Empty); outhtml = outhtml.Trim(); writer.Write(outhtml); }
禁用不必要的viewstate:这个大家都知道,页面中看不懂的长串字符就是viewstate,这大概会占用15%~40%左右的html代码量,减少viewstate势在必行,如果当前页面没有使用任何viewstate,而且又不想一个控件一个控件的关闭它,可以使用以下代码
protected override void Render(HtmlTextWriter writer) { System.IO.StringWriter html = new System.IO.StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(html); base.Render(tw); string outhtml = html.ToString(); outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "<input\\stype=\"hidden\"\\sname=\"__VIEWSTATE\"\\sid=\"__VIEWSTATE\" value=\".+\\/>", string.Empty); outhtml = outhtml.Trim(); writer.Write(outhtml); }
希望本文所述对大家的C#程序设计有所帮助