静态化页面的实现
静态页面包括纯静态和伪静态
//替换模版中的内容
public bool WriteFile(string strText,string strContent,string strAuthor)
{
string path = HttpContext.Current.Server.MapPath( "/TesConvert/news/ ");//定义html文件存放路径
Encoding code = Encoding.GetEncoding( "gb2312 ");//定义文字编码
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath( "/TesConvert/text.html ");
StreamReader sr=null;
StreamWriter sw=null;
string str= " ";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
}
catch(Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
sr.Close();
}
string htmlfilename=path + DateTime.Now.ToString( "yyyyMMddHHmmss ")+ ".html ";
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str = str.Replace( "ShowArticle ",strText); //模板页中的ShowArticle
str = str.Replace( "title ",strText);
str = str.Replace( "content ",strContent);
str = str.Replace( "author ",strAuthor);
// 写文件
try
{
sw = new StreamWriter(htmlfilename,false,code);
sw.Write(str);
sw.Flush();
}
catch(Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
return true;
}
}
}
//模版页面
2、TestNews.aspx文件:
添加三和TextBox分别为:tbx_Title、tbx_Content、tbx_Author和一个Button:btn_AddNews。
TestNews.aspx.cs文件
private void btn_AddNews_Click(object sender, System.EventArgs e)
{
MyConvert Hover = new MyConvert();
if(Hover.WriteFile(this.txb_Title.Text.ToString(),Server.HtmlDecode(this.txb_Content.Value),this.txb_Author.Text.ToString()))
{
Response.Write( "添加成功 ");
}
else
{
Response.Write( "生成HTML出错! ");
}
}
3、添加模板text.html文件
<head> ShowArticle </head>
<body>
title <br/>
content <br/>