动态创建HTML页(有详细的注释)

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值