.net生成静态页面的简单示例

发布时间:2020-12-15编辑:脚本学堂
分享一例asp.net中生成静态页面的代码,很简单,适合用来研究下生成静态页的原理,有需要的朋友参考下吧。

本节内容:
.net生成静态页面

例子:
 

复制代码 代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.IO;

public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //生成静态页
        string path = HttpContext.Current.Server.MapPath("/hello");
        Encoding code = Encoding.GetEncoding("gb2312");
        // 读取模板文件
        string aa=Server.MapPath(Request.ApplicationPath);
        string temp = Server.MapPath("/hello/tem/model.htm");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        { // www.jb200.com
            sr = new StreamReader(temp, code);
            str = sr.ReadToEnd(); // 读取文件
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sr.Close();
        }

        string fileName = "index.html";//生成之后的文件名
        string contentNew = "123123123123123";
        str = str.Replace("{$bfbstr$}", contentNew);

        try
        {
            sw = new StreamWriter(path+"/hello/"+ fileName, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
    }
}