---
title: "ASP.Net自动批量生成HTML页面和索引页"
author: "piperzero"
date: "2008-05-19T02:30:00Z"
tags: []
slug: "asp-net-html"
draft: false
lastmod: "2008-05-19T02:30:00Z"
id: 1010007
url: "https://piperzero.iteye.com/blog/1010007"
---

前天在园子里把[在ASP.net中网站访问量统计方法](http://www.tzwhx.com/newoperate/html/1/11/113/13008.html "在asp.net中网站访问量统计方法") 一文贴了上去，觉得对刚学做网站的朋友还有点用处，也有好多朋友留言鼓励，也有朋友指出了存在的问题，对我很受启发。今天是休息日，我就把在“[独上高楼](http://www.tzwhx.com/)”网站上原创一这篇文章又贴了上来，敬请朋友指教，本文是参考了[大型网站新闻系统如何生成静态网页](http://www.tzwhx.com/newoperate/html/1/11/112/964.html)、[ASP.NET生成静态网页的方法](http://www.tzwhx.com/newoperate/html/2/21/212/869.html) 等文章后形成的思路，同时在本人网站上实现了批量转换。以下所发布的代码均为我个人网站实际运行的代码，读者可以作适当的修改后相信能在你的系统中运行。

本网站新闻分类为三级，即大类、小类、三级类，主页面为VS.net动态页面，要实现一次性自动批量生成HTML页面和索引页面，需要解决如下问题：

１．在添加和修改文章时，自动生成HTML页面；

２．根据新闻分类自动判断和创建存储HTML页面的目录；

３．按三级类、小类、大类自动批量生成HTML页面，或者一次性生成所有的HTML页面和HTML索引页面；

**一、根据新闻分类自动判断和创建存储HTML页面的目录**

在添加和修改新闻时，需要对新闻所属类别进行选择或者确认，本网站就是根据新闻三级分类来创建存储HTML页面目录的，所有索引目录存储在“HTML”目录下，所有HTML文件存储在对应的第三级目录下，如123.html存储在：../ntml/1/11/111/123.html。HTML文件名均采用文章的ID编号命名。

自动判断和创建存储HTML页面的目录的代码如下，解释包含在代码中，这里不重复了：

![](http://www.tzwhx.com/images/upload/newupdate.jpg)//这里自动生成Html文件

//首先判断是否要创建按照ＩＤ三级文件夹

string ClassPathA = this.txtClass1.Text.Trim();　　// ClassPathＡ为大类码

string ClassPathB = this.txtClass2.Text.Trim();　　// ClassPathＢ为小类码

string ClassPathC = this.txtClass3.Text.Trim();　　// ClassPathＣ为三级类码

string news\_ClassPath = "html/" + ClassPathA + "/" + ClassPathB + "/" + ClassPathC + "/";

//HttpContext.Current.Server.MapPath(相对路径)：把相对路径转为服务器上的绝对路径。File.Exists(绝对路径)：检查是否存在绝对路径指向的文件或目录。

if (!File.Exists(HttpContext.Current.Server.MapPath("html/") + ClassPathA))

{

//System.IO.Directory.CreateDirectory(文件夹绝对路径)：建立绝对路径文件夹。

System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath("html/") + """" + ClassPathA);

}

if (!File.Exists(HttpContext.Current.Server.MapPath("html/" + ClassPathA) + ClassPathB))

{

System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath("html/" + ClassPathA) + """" + ClassPathB);

}

if (!File.Exists(HttpContext.Current.Server.MapPath("html/" + ClassPathA + "/" + ClassPathB) + ClassPathC))

{

System.IO.Directory.CreateDirectory(@HttpContext.Current.Server.MapPath("html/" + ClassPathA + "/" + ClassPathB) + """" + ClassPathC);

}

**二、在添加和修改文章时，自动生成HTML文件**

在添加和修改新闻文章时，可以生动生成HTML页面，也可以留待以后生成。本网站在添加或者修改一篇文章后是自动生成HTML页面的，代码如下：

//自动生成Html文件

string news\_title=this.txtTitle.Text;

string strBody = Server.HtmlDecode(this.FreeTextBox1.Text.Trim());

**strBody = strBody.Replace(System.Web.HttpUtility.HtmlDecode(""), "");**　//去掉代替空格显示的“？”号

string news\_Body = strBody;

string news\_id=Request.QueryString\["articleID\_int"].ToString();

string news\_Writer=this.txtWriter.Text;

string news\_Source = this.txtsource.Text;

string news\_Dateantime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

bool result = HtmlDB.WriteFile\_1(news\_title, news\_Body, news\_id, news\_Writer, news\_Source, news\_Dateantime, news\_ClassPath);

if (result)

{

Response.Write("〈script〉alert(""生成HTML页面成功"");〈/script〉");

}

else

{

}

这里的关键是黑体字部分，因为需要把**HtmlDecode**中的一些如**""**符号转换为空格，还有一些不明不白的符号，我也弄不清楚，必需要转换一下，修改时从数据库中读取也是一样需要转换。其他的代码相信大家能看懂的。

**三、自动批量生成HTML页面和索引页**

需要说明的是，本程序首先由新闻数据库创建了一个强类型的DataSet，以下代码均针对强类型数据集进行操作，关于强类型数据集不在本文论讨的范围之内，你可以在这里得到有关创建数据访问层和强类型的知识（http://whx.tzgt.gov.cn/newshow/newBodyShow.aspx?articleID=688），里不加表述。如果对强类型数据集不熟悉，也可以直接对数据库进行操作以获取数据。

１．创建一个HTML页面模板

创建一个名为HtmlModule.htm模板，用以统一所生成的HTML页面的格式，创建一个名叫HtmlModuleAllNews.htm的模板页面，用于生成索引页面。在创建HTML页面时系统实际上是读取该模板，然后添加替换有关内容后而生成HTML页面的。关于HTML页面模板你可以自己做一个HTML页面，由于我的HtmlModule.htm模板代码较大，所以用索引页面的模板HtmlModuleAllNews.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〉**{txtTitle}**〈/title〉

〈meta http-equiv="Content-Type" content="text/html; charset=gb2312" /〉

〈/head〉

〈body〉

〈table style="width: 800px; border-right: #666699 1px solid; border-top: #666699 1px solid; border-left: #666699 1px solid; border-bottom: #666699 2px solid;"〉

〈tr〉

〈td align="center" style="font-size: 24px; color: #ffffff; height: 60px; background-color: #669999"〉

{txtTitle}

〈/td〉

〈/tr〉

〈tr〉

〈td style="background-color: #e3ffff"〉

〈br /〉

**{content}**

〈/td〉

〈/tr〉

〈tr〉

〈td style="height: 80px; background-color: #99cc99" align="center"〉

〈span style="color: #003366"〉泰州市国土资源局〈/span〉 〈span style="color: #ff0066"〉王宏喜〈br /〉

〈span style="color: #660033"〉地址〈/span〉〈span style="color: #000000"〉：〈/span〉〈span

style="color: #000066"〉泰州市凤凰东路号〈/span〉〈span style="color: #000000"〉 〈/span〉

〈span style="color: #990066"〉邮编〈/span〉〈span style="color: #000000"〉：〈br /〉

〈span style="color: #990066"〉电话〈/span〉：〈span style="color: #000066"〉0523-6883033 电子邮件〈/span〉：〈span

style="color: #0000ff"〉Tzgtwhx@163.com 〈span style="color: #ff0066"〉QQ：〈/span〉〈/span〉〈/span〉〈/span〉〈/td〉

〈/tr〉

〈/table〉

〈/body〉

〈/html〉

注意，加黑地方的**{txtTitle}、{content}**就是需要替换的内容。

２．创建一个自动生成Html页面的的公共类

创建一个名叫HtmlDB.cs的公共类，它的作用主要是生成Html页面和索引页面。其类代码如下：

using System;

using System.Data;

using System.Configuration;

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.Text;

using System.IO;

///

/// DB 的摘要说明

///

public class HtmlDB

{

public HtmlDB()

{

//

// TODO: 在此处添加构造函数逻辑

//

}

　　//以下WriteFile\_1（）用于生成HTML页面

public static bool WriteFile\_1(string news\_title, string news\_Body, string news\_id, string news\_Writer, string news\_Source, string news\_Dateantime, string news\_ClassPath)

{

//申明字符编码,命名空间System.Text

Encoding encoding = Encoding.GetEncoding("gb2312");

//读取模板文件

string TemplatePath = HttpContext.Current.Server.MapPath("HtmlModule.htm");//

//StreamReader实现一个 TextReader，使其以一种特定的编码从字节流中读取字符，命名空间System.IO。

StreamReader sr = null;

//StreamWriter实现一个 TextWriter，使其以一种特定的编码向流中写入字符，命名空间Syste.IO。

StreamWriter sw = null;

string str = "";

try

{

sr = new StreamReader(TemplatePath, encoding);

//从流的当前位置到末尾读取流

str = sr.ReadToEnd();

}

catch (Exception e1)

{

HttpContext.Current.Response.Write(e1.Message);

HttpContext.Current.Response.End();

}

finally

{

sr.Close();

sr.Dispose();

}

//生成路径

//string myPath = "html/";

string myPath = news\_ClassPath;

string OutPutPath = HttpContext.Current.Server.MapPath(myPath);

//生成的文件名

//string newName = DateTime.Now.ToString("yyyyMM\_") + news\_id + ".html";

string newName = news\_id + ".html";

//替换内容

str = str.Replace("{title}", news\_title);

str = str.Replace("{content}", news\_Body);

str = str.Replace("{txtTitle}", news\_title);

str = str.Replace("{txtWriter}", news\_Writer);

str = str.Replace("{txtSource}", news\_Source);

str = str.Replace("{txtDateantime}", news\_Dateantime);

//str = str.Replace("{newID}", news\_id);

//写文件

try

{

sw = new StreamWriter(OutPutPath + newName,false, encoding);

sw.Write(str);

//清理当前编写器的所有缓存区，并将缓存数据写入基础流。

sw.Flush();

}

catch (Exception e2)

{

HttpContext.Current.Response.Write(e2.Message);

HttpContext.Current.Response.End();

}

finally

{

sw.Close();

sw.Dispose();

}

return true;

}

　　//以下WriteFileAllNew（）用于生成HTML索引页

public static bool WriteFileAllNew(string fileTitle, string fileBody, string filePath, string FileName)

{

//申明字符编码,命名空间System.Text

Encoding encoding = Encoding.GetEncoding("gb2312");

//读取模板文件

string TemplatePath = HttpContext.Current.Server.MapPath("HtmlModuleAllNews.htm");//

//StreamReader实现一个 TextReader，使其以一种特定的编码从字节流中读取字符，命名空间System.IO。

StreamReader sr = null;

//StreamWriter实现一个 TextWriter，使其以一种特定的编码向流中写入字符，命名空间Syste.IO。

StreamWriter sw = null;

string str = "";

try

{

sr = new StreamReader(TemplatePath, encoding);

//从流的当前位置到末尾读取流

str = sr.ReadToEnd();

}

catch (Exception e1)

{

HttpContext.Current.Response.Write(e1.Message);

HttpContext.Current.Response.End();

}

finally

{

sr.Close();

sr.Dispose();

}

//生成路径

//string myPath = "html/";

string myPath = filePath;

string OutPutPath = HttpContext.Current.Server.MapPath(myPath);

//生成的文件名

//string newName = DateTime.Now.ToString("yyyyMM\_") + news\_id + ".html";

string newName = FileName + ".html";

//替换内容

str = str.Replace("{txtTitle}", fileTitle);

str = str.Replace("{content}", fileBody);

//写文件

try

{

sw = new StreamWriter(OutPutPath + newName, false, encoding);

sw.Write(str);

//清理当前编写器的所有缓存区，并将缓存数据写入基础流。

sw.Flush();

}

catch (Exception e2)

{

HttpContext.Current.Response.Write(e2.Message);

HttpContext.Current.Response.End();

}

finally

{

sw.Close();

sw.Dispose();

}

return true;

}

}

以上代码主要有两个函数，一个是WriteFile\_1（）用于生成HTML页面，另一是WriteFileAllNew（）用于生成HTML索引页。WriteFile\_1（）共有七个参数，其中：

news\_title：用于替换HTML页面的标题；

news\_Body：用于替换HTML页面的正文

news\_id：为文章的ＩＤ号；

news\_Writer：用于替换HTML页面的作者姓名；

news\_Source：用于替换HTML页面的文章来源；

news\_Dateantime：用于替换HTML页面的时间；

news\_ClassPath：为存储HTML页面文件的路径；

关于WriteFileAllNew（）参数基本与WriteFile\_1（）参数含义相似，不多叙述。

３．创建生成Html页的Web页面

本系统中将生成Html页的Web页面取名为aspxToHtml.aspx，页面视图如下，主要由三个DropDownList控件和五个Button控件组成，三个DropDownList控件用于选择新闻分类，五个Button控件用于选择自动生成的类型。如选择生成“大类”，则自动生成这一大类的所有Html页，并自动生成这一大类的索引页，以此类推。如果选择“全部”，则生成本网站的所有新闻的Html页，并生成一个总的索引页。

![](http://www.tzwhx.com/images/upload/aspxtohtml.jpg)

aspxToHtml.aspx页的后台代码如下：

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.Data.SqlClient;

using System.IO;

public partial class newOperate\_aspxTohtml : System.Web.UI.Page

{

protected void Page\_Load(object sender, EventArgs e)

{

this.Button5.Attributes.Add("Onclick", "window.close();"); //在本地关闭当前页，而不需要发送到服务器去关闭当前页时

if (!Page.IsPostBack)

{

//自动检索二级类

SqlConnection con = db.createconnection();

con.Open();

SqlCommand cmd = new SqlCommand("select classID\_2,classname from Menulclass\_2where classID=1", con);

SqlDataReader sdr = cmd.ExecuteReader();

this.ddlnewclass2.DataSource = sdr;

this.ddlnewclass2.DataTextField = "classname";

this.ddlnewclass2.DataValueField = "classID\_2";

//classID\_b = (int)(this.ddlnewclass2.DataValueField);

this.ddlnewclass2.DataBind();

con.Close();

//自动检索三级类

SqlConnection con1 = db.createconnection();

con1.Open();

SqlCommand cmd1 = new SqlCommand("select classID\_3,classname from Menulclass\_3where classID\_2=11", con1);

SqlDataReader sdr1 = cmd1.ExecuteReader();

this.ddlnewclass3.DataSource = sdr1;

this.ddlnewclass3.DataTextField = "classname";

this.ddlnewclass3.DataValueField = "classID\_3";

this.ddlnewclass3.DataBind();

con1.Close();

}

}

protected void ddlnewclass\_SelectedIndexChanged(object sender, EventArgs e)

{

//当选择了大类按钮，则自动填充小类的内容

this.ddlnewclass2.Items.Clear();

SqlConnection con = db.createconnection();

con.Open();

//Response.Write(this.ddlnewclass.SelectedItem.Value);

SqlCommand cmd = new SqlCommand("select classID\_2,classname from Menulclass\_2where classID=" + this.ddlnewclass1.SelectedValue, con);

SqlDataReader sdr = cmd.ExecuteReader();

this.ddlnewclass2.DataSource = sdr;

this.ddlnewclass2.DataTextField = "classname";

this.ddlnewclass2.DataValueField = "classID\_2";

this.ddlnewclass2.DataBind();

con.Close();

//自动填充三级类的内容

this.ddlnewclass3.Items.Clear();

SqlConnection conn = db.createconnection();

conn.Open();

//Response.Write(this.ddlnewclass2.SelectedItem.Value);

SqlCommand cmdn = new SqlCommand("select classID\_3,classname from Menulclass\_3where classID\_2=" + this.ddlnewclass2.SelectedValue, conn);

SqlDataReader sdrn = cmdn.ExecuteReader();

this.ddlnewclass3.DataSource = sdrn;

this.ddlnewclass3.DataTextField = "classname";

this.ddlnewclass3.DataValueField = "classID\_3";

this.ddlnewclass3.DataBind();

conn.Close();

}

protected void ddlnewclass2\_SelectedIndexChanged(object sender, EventArgs e)

{

//当选择了小类按钮，则自动填充三级类的内容

this.ddlnewclass3.Items.Clear();

SqlConnection conn = db.createconnection();

conn.Open();

//Response.Write(this.ddlnewclass2.SelectedItem.Value);

SqlCommand cmdn = new SqlCommand("select classID\_3,classname from Menulclass\_3where classID\_2=" + this.ddlnewclass2.SelectedValue, conn);

SqlDataReader sdrn = cmdn.ExecuteReader();

this.ddlnewclass3.DataSource = sdrn;

this.ddlnewclass3.DataTextField = "classname";

this.ddlnewclass3.DataValueField = "classID\_3";

this.ddlnewclass3.DataBind();

conn.Close();

}

protected void ddlnewclass3\_SelectedIndexChanged(object sender, EventArgs e)

{

//this.BindToGridViewBody();//调用下面的BindToGridViewBody()绑定数据

}

public static bool htmlMapPath(string ClassPathA, string ClassPathB, string ClassPathC)

{