在這里,我將一些新聞從數(shù)據(jù)庫(kù)讀取后,以靜態(tài)化形式顯示出來(lái)。
先找一個(gè)靜態(tài)頁(yè)面模板,如下:

注意頁(yè)面中的NewsTitle和NewsContent標(biāo)簽
下面我們?cè)谝粋€(gè)按鈕的事件方法中寫(xiě)生成代碼:
string aid = this.GridView1.DataKeys[e.RowIndex]["ArticleID"].ToString();
SqlConnection conn = new SqlConnection("server=.;database=tb_News;uid=sa;pwd=");
SqlCommand cmd = new SqlCommand("select * from tb_Ariticle where ArticleID=" + aid, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
//獲取新聞發(fā)布的時(shí)間
string date = "";
if (dr.Read())
{
date = Convert.ToDateTime(dr["RelaseDate"]).ToString("yyyyMMddHHmmss_");//獲取時(shí)間是為了生成的時(shí)候構(gòu)造文件民名
//調(diào)用靜態(tài)生成方法
TransferStatic(dr["Title"].ToString(), dr["Content"].ToString(), date, aid);
}
/// <summary>
/// 轉(zhuǎn)換方法
/// </summary>
/// <param name="title"></param>
/// <param name="content"></param>
/// <param name="date"></param>
/// <param name="aid"></param>
/// <returns></returns>
private bool TransferStatic(string title,string content,string date,string aid)
{
//輸出路徑
string outPath = Server.MapPath("~/News\\");
Encoding encoding = Encoding.GetEncoding("gb2312"); //定義轉(zhuǎn)換的編碼格式
//讀取模板文件:這個(gè)是為了下面利用模板
string htmlModel = Server.MapPath("~/mode/ContentModel.html");
//利用流的方法
StreamWriter sw = null;
StreamReader sr = null;
string str = ""; //保存從模板文件中讀取的內(nèi)容以及后面替換的內(nèi)容
//讀文件
try
{
sr = new StreamReader(htmlModel, encoding);
str = sr.ReadToEnd(); //將模板文件讀取到字符串str中
}
catch(Exception e)
{
Response.Write(e.Message);
Response.End();
sr.Close();
}
//構(gòu)造要生成的靜態(tài)頁(yè)面的名字
string pageName = date + aid + ".html";
//開(kāi)始替換內(nèi)容
str = str.Replace("NewsTitle",title);//第一個(gè)參數(shù)是要替換的內(nèi)容部分
str = str.Replace("NewsContent", content);
//寫(xiě)文件
try
{
sw = new StreamWriter(outPath + pageName, true, encoding);
sw.Write(str);//將字符串str寫(xiě)入到文件
sw.Flush(); //這個(gè)最好不好忘記
}
catch (Exception e)
{
Response.Write(e.Message);
Response.End();
}
finally
{
sw.Close();
}
return true;
}
我們打開(kāi)News目錄,就會(huì)發(fā)現(xiàn)我們剛才生成的頁(yè)面。