public string CreateHtml(string NewsTitle,string NewsContent)
{//创建HTML页
string path = HttpContext.Current.Server.MapPath("../NewsHtml/");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath("../NewsHtml/NewsTemplet.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=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
//为准备用于替换模板中内容的变量赋值
str =str.Replace("$NewsTitle$",NewsTitle);
str = str.Replace("$NewsContent$",NewsContent);
str = str.Replace("$AddTime$",DateTime.Now.ToString("yyyy-MM-dd"));
//News为实体类,只适合本人的项目,按照本文来编写代码的朋友可将News.改为string即可。
News.Url = path + htmlfilename;
// 写文件
try
{
//指定要写入数据的文件路径以及字符编码方式
sw = new StreamWriter(News.Url,false,code);
//将已赋值的变量中的内容替换模板中的内容
sw.Write(str);
//使所有的数据写入流,并且清理缓冲区
sw.Flush();
return News.Url;
}
catch(Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
return "";
}
finally
{
//关闭数据写入流
sw.Close();
}
------创建模板文件NewsTemplet.html------
<html>
<head>
<title>本人菜鸟,大家一起学习交流</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000">
<tr>
<td width="70%" valign="middle" align="left">
$NewsTitle$</td><td width="30%" valign="middle" align="left"> $AddTime$</td>
</td>
</tr>
<tr><td width=100% align=center>$NewsContent$</td></tr>
</table>
</body>
</html>