新聞門戶、文章系統常需將長文內容分頁生成靜態 HTML 檔案(如 article_1.html、article_2.html),以降低資料庫壓力、提升瀏覽速度、利於 SEO。本文實作完整動態生成靜態分頁系統:資料庫讀取 → 內容分頁切割 → 模板標記替換 → 靜態檔案寫入目錄。
$title、$content、$page)。/news/get/)。public partial class Solid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 範例:生成標題「奧運專題」,內容分 2 頁
WriteFile("奧運專題", "奧運會真棒!\n內容很長...", "2", "2.html");
}
public void WriteFile(string strText, string content, string page, string name)
{
string path = HttpContext.Current.Server.MapPath("~/news/get");
Encoding code = Encoding.GetEncoding("gb2312"); // 或 UTF-8
// 1. 讀取模板
string templatePath = HttpContext.Current.Server.MapPath("~/news/text.htm");
string templateContent;
using (StreamReader sr = new StreamReader(templatePath, code))
{
templateContent = sr.ReadToEnd();
}
// 2. 替換標記
string html = templateContent
.Replace("$title", strText)
.Replace("$content", content)
.Replace("$page", page);
// 3. 確保目錄存在
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
// 4. 寫入靜態檔案
string filePath = Path.Combine(path, name);
using (StreamWriter sw = new StreamWriter(filePath, false, code))
{
sw.Write(html);
}
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>無標題頁</title>
</head>
<body>
<div style="font-size:20px; text-align:center;">文章分頁測試</div>
<div style="font-size:15px; text-align:center; color:#009966;">$title</div>
<div style="font-size:12px; text-align:center; color:darkgray;">$page</div>
<div style="font-size:12px;">$content</div>
</body></html>
public List SplitContent(string fullContent, int pageSize)
{
var pages = new List();
for (int i = 0; i < fullContent.Length; i += pageSize)
{
int len = Math.Min(pageSize, fullContent.Length - i);
pages.Add(fullContent.Substring(i, len));
}
return pages;
}
// 批次生成所有分頁
public void GenerateAllPages(string title, string fullContent, int pageSize, string baseName)
{
var pages = SplitContent(fullContent, pageSize);
for (int i = 0; i < pages.Count; i++)
{
string pageNav = BuildPageNavigation(baseName, pages.Count, i + 1);
WriteFile(title, pages[i], pageNav, $"{baseName}_{i+1}.html");
}
}
private string BuildPageNavigation(string baseName, int totalPages, int currentPage)
{
var sb = new StringBuilder();
for (int i = 1; i <= totalPages; i++)
{
if (i == currentPage)
sb.Append($"{i} ");
else
sb.Append($"{i} ");
}
return sb.ToString();
}
/news/
/get/ ← 靜態 HTML 輸出目錄(需寫入權限)
article_1.html
article_2.html
...
text.htm ← 模板檔案
solid.aspx ← 生成觸發頁面(管理後台呼叫)
HttpRuntime.Cache 快取模板內容,避免重複磁碟讀取。ThreadPool.QueueUserWorkItem 或 BackgroundWorker 離線生成,避免請求逾時。/news/get/ 僅需靜態檔案讀取權限,禁止執行腳本(IIS 移除腳本對應)。動態生成靜態分頁系統以「寫入時計算、讀取時極速」架構,支撐高流量內容型網站核心效能需求。