c#.net关于生成html静态页面的问题...
时间:2010-08-18 来源:zhaoqiliang527
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>$ShowArticle$</title>
<body>
标题:$biaoti$
<br/>
内容开始<br/><br/>
$content$<br/>
<br/><br/>作者:$author$
<br/>结束
</body>
</HTML>
2。代码文件
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class htm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnOk_Click(object sender, EventArgs e)
{
string a, b, c, d;
a = "这是一个title";
b = "这是一个标题";
c = "这里是内容";
d = "这是作者";
if (WriteFile(a, b, c, d))
{
Response.Write("添加成功");
}
else
{
Response.Write("生成HTML出错!");
}
}
//
public static bool WriteFile(string strText, string Biaoti, string strContent, string strAuthor)
{
string path = HttpContext.Current.Server.MapPath("./");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath("Text.htm");
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 = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str = str.Replace("$ShowArticle$", strText); //模板页中的ShowArticle
str = str.Replace("$biaoti$", Biaoti);
str = str.Replace("$content$", strContent);
str = str.Replace("$author$", strAuthor);
// 写文件
try
{
sw = new StreamWriter(path + 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;
}
}