採用「模板替換 + 伺服器端生成」模式:前端編輯內容 → 後端讀取模板 → 替換標記 → 切割長文 → 生成多個 .shtml 靜態檔案 → 存入資料庫記錄路徑。
預留標記:Title、NewsId、Time、Content、Pager,供後端程式替換。
<div align="center">Title</div>
<div>瀏覽 <font color="red"><script src="/ClickCount.aspx?NewsId=NewsId"></script></font> 次 Time</div>
<div>Content</div>
<div>Pager</div> <!-- 分頁導航將注入此處 -->
使用 FCKeditor 富文本編輯器,表單包含標題與內容兩欄位。
| 字元分割長文,每段生成一個分頁。NewsFiles/240115/),避免單一目錄檔案過多。StreamReader 讀取模板,StringBuilder 累加替換後內容。FileStream + StreamWriter 輸出 .shtml 檔案。protected void Button1_Click(object sender, EventArgs e)
{
string strDate = DateTime.Now.ToString("yyMMddHHmmss");
string strFileName = strDate + ".shtml";
string strTitle = Request.Form["Title"].Trim();
string strContent = Request.Form["Content"].Trim();
string[] contents = strContent.Split('|');
int pageCount = contents.Length;
// 存入資料庫略...
string dir = Server.MapPath($"~/NewsFiles/{DateTime.Now:yyMMdd}");
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
for (int i = 0; i < pageCount; i++)
{
StringBuilder html = new StringBuilder();
// 讀取模板
using (StreamReader sr = new StreamReader(Server.MapPath("~/NewsFiles/template.html"), Encoding.GetEncoding("gb2312")))
{
string line;
while ((line = sr.ReadLine()) != null) html.Append(line);
}
// 替換通用標記
html.Replace("Title", strTitle);
html.Replace("NewsId", newId.ToString());
html.Replace("Time", DateTime.Now.ToString("yyyy/MM/dd"));
html.Replace("Content", contents[i]);
// 生成分頁導航 HTML (strTable)
// ... 邏輯處理 upUrl, Number, downUrl 替換 ...
html.Replace("Pager", strTable);
// 寫入檔案
string filePath = (i == 0)
? Path.Combine(dir, strDate + ".shtml")
: Path.Combine(dir, $"{strDate}_{i}.shtml");
using (FileStream fs = new FileStream(filePath, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.Write(html.ToString());
}
}
}
System.Text.Json 序列化模型,提升可維護性。async/await) 避免阻塞請求執行緒。