ASP.NET產生靜態頁面的簡單實現

來源:互聯網
上載者:User

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;/// <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;    }}

 

執行個體下載

 

作者: ForEvErNoME
出處: http://www.cnblogs.com/ForEvErNoME/
歡迎轉載或分享,但請務必聲明文章出處。如果文章對您有協助,希望你能 推薦 或 關注

     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.