首页 > 代码库 > 生成静态页面方法 .NET
生成静态页面方法 .NET
原文发布时间为:2009-09-30 —— 来源于本人的百度文章 [由搬家工具导入]
采用模板法:【例子中的两个页面以及生成的页面均在同一个目录,自己可以去改】
模板Template.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>标题:$htmlformat[0]</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
<div style="text-align: center;">
内容
</div>
<div style="text-align: center; font-size: 16px; font-weight: bold;$htmlformat[1]">$htmlformat[2]
</div>
</body>
</html>
后台程序:
using System;
using System.Data;
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;
using System.IO;
using System.Text;
public partial class ChangeToHtml : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ToHTML();
}
protected void ToHTML()
{
string[] format = new string[3];//定义和htmlformat标记数目一致的数组
StringBuilder htmltext = new StringBuilder();
try
{
using (StreamReader sr = new StreamReader(Server.MapPath("Template.htm"), Encoding.GetEncoding("GB2312")))
{
String line;
while ((line = sr.ReadLine()) != null)
{
htmltext.Append(line);
}
sr.Close();
}
}
catch
{
Response.Write("<script>alert('读取文件错误')</script>");
}
//--------给标记数组赋值-----------//
format[0] = "静态页面生成";
format[1] = "color:red";
format[2] = "生成了静态HTML";
//-------替换html里的标记为你想加的内容-----------//
for (int i = 0; i < 3; i++)
{
htmltext.Replace("$htmlformat[" + i + "]", format[i]);
}
//----------生成html文件------------//
try
{
using (StreamWriter sw = new StreamWriter(Server.MapPath(DateTime.Now.ToString("yyyyMMddHHmmss") + ".htm"), false, Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(htmltext);
sw.Flush();
sw.Close();
}
}
catch
{
Response.Write("<script>alert('文件生成失败')</script>");
}
}
}
生成静态页面方法 .NET