• .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);
    }
    }
    庆幸的是我,一直没回头。
  • 相关阅读:
    洛谷P4016 负载平衡问题 费用流
    Reactor Cooling ZOJ
    Acme Corporation UVA
    洛谷P4014 分配问题 费用流
    洛谷P4013 数字梯形问题 费用流
    洛谷P4012 深海机器人问题 费用流
    力扣题目汇总(旋转数字,移除元素,找不同)
    力扣题目汇总(两数之和Ⅱ-输入有序数组,删除排序数组中的重复项,验证回文串)
    逻辑练练手小程序
    爬虫之Scarpy.Request
  • 原文地址:https://www.cnblogs.com/rocblog/p/3108513.html
Copyright © 2020-2023  润新知