.net动态生成静态页面的一种方法
先弄一个静态页面模板: <!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> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>$htmlkey[0]</title> </head> <body> <table width="200" border="1"> <tr> <td colspan="2" align="center" valign="middle" bgcolor="#999999">$htmlkey[1]</td> </tr> <tr> <td width="96">$htmlkey[2]</td> <td width="88">$htmlkey[3]</td> </tr> <tr> <td colspan="2" align="center" valign="middle" bgcolor="#CCCCCC">$htmlkey[4]</td> </tr> </table> </body> </html> 里面类似$htmlkey[x]的就是要动态替换的位置。 。net前台弄几个控件用于用户输入要插入模板生成新静态网页的内容,比如textbox。后台当点击按钮时替换模板的那几个需要替换的部分,再保存静态页面到一个指定的目录就OK。 后台为: protected void Button1_Click(object sender, EventArgs e) { string[] newContent= new string[5]; StringBuilder strhtml = new StringBuilder(); string path=Server.MapPath("newHTML")+"\\template.html"; try { StreamReader sr = new StreamReader(path); String oneline; while ((oneline = sr.ReadLine()) != null) { strhtml.AppendLine(oneline); } sr.Close(); } catch (Exception err) { Response.Write(err); } newContent[0] = TextBox1.Text; newContent[1] = TextBox1.Text; newContent[2] = DateTime.Now.ToString(); newContent[3] = TextBox2.Text; newContent[4] = TextBox3.Text; try { string fname = Server.MapPath("newHTML") + "\\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html"; for (int i = 0; i < 5; i++) { strhtml.Replace("$htmlkey[" + i + "]", newContent[i]); } //代码存到StringBuilder strhtml里面了。 FileInfo file = new FileInfo(fname); FileStream fs = file.OpenWrite(); StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312")); sw.WriteLine(strhtml); sw.Flush(); //发送缓冲区中的输出 sw.Close(); } catch (Exception err) { Response.Write(err); } }
庆幸的是我,一直没回头。