本文以實例講解了asp.net實現生成靜態頁並添加鏈接的方法,非常實用的功能,通過本實例可以加深讀者對於asp.net下文件操作的認識。
1.創建一個靜態網頁模板
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>模板網頁</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" gcolor="#eeeeee" style="border:1px solid #000000"> <tr> <td width="100%" valign="middle" align="left"> <h1>$htmlformat[1]</h1> <div style="color: $htmlformat[2];font-size: $htmlformat[3]">$htmlformat[4]</div> </td> </tr> </table> </body> </html>
2.在asp.net網頁後台代碼中替換模板html頁中的標記符
protected void Button1_Click(object sender, EventArgs e) { string[] format = new string[5];//定義和htmlyem標記數目一致的數組 StringBuilder htmltext = new StringBuilder(); string templatePath = Server.MapPath("~/html/Template.html"); StreamReader sr = new StreamReader(templatePath); String line; while ((line = sr.ReadLine()) != null) { htmltext.Append(line); } sr.Close(); //---------------------給標記數組賦值------------ format[0] = "background=\"bg.jpg\"";//背景圖片 format[1] = TB_Title.Text; format[2] = "#990099"; //字體顏色 format[3] = "60px";//文字大小 format[4] = TB_Content.Text; //----------替換htm裡的標記為你想加的內容 for (int i = 0; i < 5; i++) { htmltext.Replace("$htmlformat[" + i + "]", format[i]); } //----------生成htm文件------------------―― string newfile = Server.MapPath("~/html/"+TB_Title.Text+".html"); StreamWriter sw = new StreamWriter(newfile, false, System.Text.Encoding.GetEncoding("GB2312")); sw.WriteLine(htmltext); sw.Flush(); sw.Close(); string newhref="html/" rel="external nofollow" +TB_Title.Text+".html"; Response.Write("<a href=\"" + newhref + "\">" + TB_Title.Text + "</a>"); }