您现在的位置是:网站首页> 编程资料编程资料

ASP.NET编程简单实现生成静态页面的方法【附demo源码下载】_实用技巧_

2023-05-24 265人已围观

简介 ASP.NET编程简单实现生成静态页面的方法【附demo源码下载】_实用技巧_

本文实例讲述了ASP.NET编程简单实现生成静态页面的方法。分享给大家供大家参考,具体如下:

1. 使用场景

当页面的数据不需要经常更改时可采用静态页面方式。

2. 使用静态页面的好处

(1)提高网站的访问速度

(2)减轻服务器负担

(3)利于搜索引擎抓取

3. ASP.NET生成静态页面

生成静态页面方法有很多种,先说下我使用的其中的一种。参考资料

基本思路:

(1)创建模板template.html文件,在里面定义一些特殊的字符串格式用于替换内容,如$htmlformat

(2)读取模板,赋值到StringBuilder对象中

(3)将特殊的字符串格式替换为你想要的内容

(4)创建新的静态页面,并将StringBuilder对象写入到文件中即可

4. 方法

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.IO; ///  ///ConvertHtmlPage 生成静态页面 ///  public class ConvertHtmlPage { ///  /// 生成HTML文件 ///  /// 模板路径 /// 模板名称 /// 生成HTML的路径 /// 生成HTML的名称 /// 替换的内容 ///  public static bool CreatePage(string templatePath,string templateName, string htmlPath, string htmlName,List format) { try { //读取模板文件 StringBuilder htmltext = new StringBuilder(); using (StreamReader sr = new StreamReader(templatePath+templateName)) { string line; while ((line = sr.ReadLine()) != null) { htmltext.AppendLine(line); } sr.Close(); } //替换HTML中的标记内容 for (int i = 0; i < format.Count; i++) { htmltext.Replace("$htmlformat[" + i + "]", format[i]); } //生成HTML文件 using (StreamWriter sw = new StreamWriter(htmlPath+htmlName, false, System.Text.Encoding.GetEncoding("GB2312"))) { sw.WriteLine(htmltext); sw.Flush(); sw.Close(); } } catch (Exception ex) { return false; } return true; } } 

附:DEMO实例点击此处本站下载

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net文件操作技巧汇总》、《asp.net操作json技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。

-六神源码网