本文實例講述了ASP.NET編程簡單實現生成靜態頁面的方法。分享給大家供大家參考,具體如下:
1. 使用場景
當頁面的數據不需要經常更改時可采用靜態頁面方式。
2. 使用靜態頁面的好處
(1)提高網站的訪問速度
(2)減輕服務器負擔
(3)利于搜索引擎抓取
3. ASP.NET生成靜態頁面
生成靜態頁面方法有很多種,先說下我使用的其中的一種。參考資料
基本思路:
(1)創建模板template.html文件,在里面定義一些特殊的字符串格式用于替換內容,如$htmlformat
(2)讀取模板,賦值到StringBuilder對象中
(3)將特殊的字符串格式替換為你想要的內容
(4)創建新的靜態頁面,并將StringBuilder對象寫入到文件中即可
4. 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.IO; /// <summary> ///ConvertHtmlPage 生成靜態頁面 /// </summary> public class ConvertHtmlPage { /// <summary> /// 生成HTML文件 /// </summary> /// <param name="templatePath">模板路徑</param> /// <param name="templateName">模板名稱</param> /// <param name="htmlPath">生成HTML的路徑</param> /// <param name="htmlName">生成HTML的名稱</param> /// <param name="format">替換的內容</param> /// <returns></returns> public static bool CreatePage( string templatePath, string templateName, string htmlPath, string htmlName,List< string > 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程序設計有所幫助。