C# 用模板生成静态页

最近在研究静态页输出的问题,找了一些资料。做了一个简单的模板模式的静态输出

模板代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>{$_title}</title>
</head>
<body>
<div style=" text-align:center">{$_Newstitle}</div>
<div>{$_NewsInfo}</div>
</body>
</html>
生成静态页的后台代码:

protected void Shencheng()
        {
            string title = "静态页输出";
            string Newstitle = "新闻标题";
            string NewInfo = "新闻内容的输入死了的房间了深刻的缴费历史的缴费历史的减肥了似的离开房间乐山大佛上的浪费空间了";
            string HtmlName = "ceshi.html";
            Fabu_Input_CS(title, Newstitle, NewInfo, HtmlName);
        }
         //生成静态页代码
        private void Fabu_Input_CS(string title, string Newstitle, string NewInfo, string HtmlName)
        {
            string path = this.MapPath("~/Cess.htm");//模板地址
            string path_str = "";
            path_str = this.MapPath("~/info")+@"/"+HtmlName;//生成静态页的保存路径
            //读取模板文件信息,设置编码为默认编码,我测试很多次,这设置编码,于我们最后生成静态文件没有直接关系。
            StreamReader read = new StreamReader(path, System.Text.Encoding.Default);
            string rl = "";
            string accc = "";
            do
            {
                accc += rl;
            } while ((rl=read.ReadLine())!=null);//读取模板数据
            read.Close();

            //替换页面内对应的内容
            accc = accc.Replace("{$_title}",title);
            accc = accc.Replace("{$_Newstitle}", Newstitle);
            accc = accc.Replace("{$_NewsInfo}", NewInfo);

            if (System.IO.File.Exists(path_str))//判断该静态页是否存在
            {
                System.IO.File.Delete(path_str);//删除该静态页
            }
            System.IO.File.AppendAllText(path_str, accc, Encoding.GetEncoding("gb2312"));//生成该静态页文件
        }

只是简单的生成静态页,对于带分页的静态页还在继续。

原文地址:https://www.cnblogs.com/xiaobeiblog/p/3376128.html