asp.net批量生成静态页的问题

polic 2009-07-21 11:51:38
前段时间做了个小的新闻系统,可是在批量生成静态页时发现好多页面的内容都重复了,然后就用了线程,延迟执行的时间,可是这样做我感觉很不合理,有的页面内容多可能需要的时间稍长点,有的页面则需要很少的时间就可以了,那样做太浪费资源和时间。于是从网站找到了用线程池来实现,可是搞了很长时间也没搞明白具体应该怎么做。知道其他好的方法也可以,小弟在此先谢过了。到时一定加分。
...全文
413 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
polic 2009-07-27
  • 打赏
  • 举报
回复
怎么都没人知道么?自己顶下
polic 2009-07-23
  • 打赏
  • 举报
回复
#7楼 能说下你的方法吗,贴段代码 出来,如果没问题分给你了
polic 2009-07-23
  • 打赏
  • 举报
回复
#11楼 你说的方法和我用的一样,问题是如果现在数据库里有很多上万条数据,然后突然有一天,需要对网站进行改版,修改了模板文件,要重新生成怎么办?如果写循环就出现了上述所说的内容重复的问题。
ff1222 2009-07-22
  • 打赏
  • 举报
回复
mark
zzs_happy 2009-07-22
  • 打赏
  • 举报
回复
呵,你的循环有问题,我的没有。
feng87558812 2009-07-22
  • 打赏
  • 举报
回复
那里要用什么线程 我给你吧 分给我 看下面代码 如果不清楚 加我QQ 我给你项目部分源代码
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
string strDate = DateTime.Now.ToString("yyMMdd") + "/" + DateTime.Now.ToString("yyyyMMddhhmmss");
string strFileName = strDate + ".html";//存储到数据库中
string strTitle = Request.Form["txttitle"].ToString().Trim();//接收传过来的标题
string strautor = Request.Form["txtautor"].ToString().Trim();
string strfrom = Request.Form["txtfro_m"].ToString().Trim();
string strContent = Request.Form["FreeTextBox1"].ToString().Trim();//接收传过来的内容
string strtime = Convert.ToString(System.DateTime.Now);


FEBS.Public.Model.TB_Add model = new FEBS.Public.Model.TB_Add();
model.title = strTitle;
model.autor = strautor;
model.fro_m = strfrom;
model.text = strContent;

model.time = Convert.ToDateTime(strtime);
model.filePath = strFileName;
FEBS.Public.BLL.TB_Add bll = new FEBS.Public.BLL.TB_Add();
bll.Add(model);

//屏蔽字 词
if (this.CheckBox1.Checked == true)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnString1"].ConnectionString))
{

conn.Open();
//string strsql = "select Username,Userpwd from TB_user where Username='" + txtname.Text + "' or Userpwd='" + txtpwd.Text + "'";
string strSQL = "SELECT text FROM TB_screen";
SqlCommand com = new SqlCommand(strSQL, conn);
SqlDataReader read;
read = com.ExecuteReader();
string str = "";
if (read.Read())
{

str = read["text"].ToString();

}


//ArrayList al = new ArrayList();
//string[] str2 =str.Split(new Char[] { ' ' });//对内容进行拆分,并保存到数组\
//int j = 0;
//foreach (string att in str2)
//{
// al.Add(str2[j]);
// strContent=strContent.Replace(Convert.ToChar(al[j]), '*');
// j++;

//}

//方法二
string[] str3 = str.Split(' ');
foreach (string att in str3)
{
int c = att.Length;

string s = "";
for (int i = 0; i < c; i++)
{
s += "*";
}
strContent = strContent.Replace(att, s);

}



}
}
//Response.Write("<script>alert('发布成功!')</script>");


string[] content = Regex.Split(strContent, "<hr>", RegexOptions.IgnoreCase);//对内容进行拆分,并保存到数组
//string[] content = strContent.Split(new Char[] {'‖'});
int upbound = content.Length;//数组的上限

///////////////////////////创建当前日期的文件夹开始
//用来生成文件夹
// string dir = Server.MapPath("../"+"NewsFiles/" + DateTime.Now.ToString("yyMMdd"));
string dir = Server.MapPath("NewsFiles/" + DateTime.Now.ToString("yyMMdd"));//用来生成文件夹

if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
/**/
///////////////////////////创建当前日期的文件夹结束
try
{

for (int i = 0; i < upbound; i++)
{
//string[] newContent = new string[4];//定义和html标记数目一致的数组
StringBuilder strhtml = new StringBuilder();

//创建StreamReader对象
//using (StreamReader sr = new StreamReader(Server.MapPath("../" + "NewsFiles/") + "\template.html", Encoding.GetEncoding("gb2312")))
using (StreamReader sr = new StreamReader(Server.MapPath("~/NewsFile/template.html")))
{
String oneline;
//读取指定的HTML文件模板
while ((oneline = sr.ReadLine()) != null)
{
strhtml.Append(oneline);
}
sr.Close();
}
string strTable = "<table><tr><td>$upUrl</td><td>$Number</td><td>$downUrl</td></tr></table>";//上下页表格,注意此处的$upUrl(上一页),$Number(页码分页),$downUrl(下一页)
//这三个是用来替换的。
string FilePath = "";
strhtml = strhtml.Replace("$Title", strTitle);
//strhtml = strhtml.Replace("NewsId", ds.Tables["temp"].Rows[0]["id"].ToString());
strhtml = strhtml.Replace("$author", strautor);
strhtml = strhtml.Replace("$form", strfrom);
strhtml = strhtml.Replace("$time", strtime);
//strhtml = strhtml.Replace("Pager", strTable);

strhtml = strhtml.Replace("$Content", content[i]);
string strNumber = "";//数字分页1,2,3……
for (int m = 1; m <= upbound; m++)
{
if (m == 1)//如果是第一页就显示成这个样子:20070524.html而不是20070524_1.html
strNumber = strNumber + " [" + "<a href=" + "../" + strDate + ".html" + ">" + m + "</a>" + "] ";
else
{
int n = m - 1;//第三页的连接应该是20070524_2.html,以此类推
strNumber = strNumber + " [" + "<a href=" + "../" + strDate + "_" + n + ".html" + ">" + m + "</a>" + "] ";
}
}
if (upbound == 0)//如果没有分页,就直接按日期时间保存
{
//FilePath = "NewsFiles" + "//" + strDate + ".html";
FilePath = Server.MapPath("~/NewsFiles/" + strDate + ".html");
strhtml = strhtml.Replace("$Pager", "");
}
else//否则按20070524.html、20070524_1.html 这种效果保存
{
if (i == 0)
//FilePath = "NewsFiles" + "//" + strDate + ".html";
FilePath = Server.MapPath("~/NewsFiles/" + strDate + ".html");
else
//FilePath = "NewsFiles" + "//" + strDate + "_" + i + ".html";
FilePath = Server.MapPath("~/NewsFiles/" + strDate + "_" + i + ".html");

if (i == 0)//第一页不显示上一页
strTable = strTable.Replace("$upUrl", "");
if (i <= 1)//上一页分页

strTable = strTable.Replace("$upUrl", "<a href=" + "../" + strDate + ".html" + ">上一页</a>");
else
{
int p = i - 1;
strTable = strTable.Replace("$upUrl", "<a href=" + "../" + strDate + "_" + p + ".html" + ">上一页</a>");
}

if (upbound == 1)//如果只有一页,则不显示页码
//strNumber="";
strTable = strTable.Replace("$Number", "");
else
strTable = strTable.Replace("$Number", strNumber);//页码替换
/**/
if (i == upbound - 1)//最后一页不显示下一页
strTable = strTable.Replace("$downUrl", "");
if (i != upbound - 1)//下一页分页
{
int q = i + 1;
strTable = strTable.Replace("$downUrl", "<a href=" + "../" + strDate + "_" + q + ".html" + ">下一页</a>");
}
else
{
int j = upbound - 1;
strTable = strTable.Replace("$downUrl", "<a href=" + "../" + strDate + "_" + j + ".html" + ">下一页</a>");
}
strhtml = strhtml.Replace("$Pager", strTable);
}
//创建文件信息对象--------------------------------------------
FileInfo finfo = new FileInfo(FilePath);
//以打开或者写入的形式创建文件流
using (FileStream fs = finfo.OpenWrite())
{
//根据上面创建的文件流创建写数据流
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
//把新的内容写到创建的HTML页面中
sw.WriteLine(strhtml);
sw.Flush();
sw.Close();
}
}

}
catch (Exception err)
{
//输出异常信息
//Response.Write("Hacker Attack!!!");
//Response.End();
Response.Write(err.ToString());
}
jyy_Emirates 2009-07-22
  • 打赏
  • 举报
回复
由于本人的空间收到限制,不能一次批量生成所有的静态页,所以自己写了一个小程序和大家分享,程序相当简单,高手莫要见笑!此代码就是很浪费时间.代码如下


<!--#include file="conn.asp"-->
<HTML><HEAD><TITLE>生成页面</TITLE>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<LINK href="style.css" type=text/css rel=stylesheet>
<META content="MSHTML 6.00.2900.3020" name=GENERATOR>
</HEAD>
<BODY bottomMargin=0 leftMargin=0 topMargin=0 rightMargin=0>
<BR style="OVERFLOW: hidden; LINE-HEIGHT: 3px">
<%
dim id
id=cint(request.querystring("id"))
if id="" then
id="1"
else
id=cint(request.querystring("id"))
end if

Dim totalnumber
sql="select id from table order by id DESC"
set rs=server.createobject("adodb.recordset")
rs.open sql,conn,1,1
rs.Movefirst
if not rs.eof then
TotalNumber=rs.recordcount
end if
获取总数可以用一句代码代替,这个相信朋友自己可以解决.
rs.close
set rs=nothing

Response.Write "<br><br>" & vbNewLine
Response.Write "<table width='400' border='0' align='center' cellpadding='0' cellspacing='0'>" & vbNewLine
Response.Write " <tr>" & vbNewLine
Response.Write " <td height='50'>总共 <font color='blue'><b>" & totalnumber & "</b></font> 个页面,正在生成第 <font color='red'><b>" & ID & "</b></font> 个页面…… </td>" & vbNewLine
Response.Write " </tr>" & vbNewLine
Response.Write "</table>" & vbNewLine
Response.Flush

If ID > totalnumber Then
Response.Write "恭喜您操作成功!"
Response.Flush
End If

creat(ID)
id=id 1
Response.Write "<meta http-equiv=""refresh"" content=""1;url=?ID="&id&""">"
%>
</BODY>
</HTML>

<%
Function creat(id)
sql="SELECT * from table where id="&ID
set rs=conn.execute(sql)
dim name
name=rs("name")
conn.execute(sql)
rs.close
set rs=nothing
dim fso
dim znwl
dim art
dim fw
set fso=createobject("scripting.filesystemobject")
set znwl=fso.opentextfile(server.mappath("模板页"))
art=znwl.readall
znwl.close

art=replace(art,"{$name$}",name)
set fw=fso.createtextfile(server.mappath("生成页存放位置及页面名称"),true)
fw.writeline art
fw.close
set fso=nothing
End Function
%>





另外还有一种方法比上面的方法快,但是占用CPU比较多,我的空间用下面的方法老出问题


<!--#include file="conn.asp"-->
<HTML><HEAD><TITLE>生成页面</TITLE>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<LINK href="style.css" type=text/css rel=stylesheet>
<META content="MSHTML 6.00.2900.3020" name=GENERATOR>
</HEAD>
<BODY bottomMargin=0 leftMargin=0 topMargin=0 rightMargin=0>
<BR style="OVERFLOW: hidden; LINE-HEIGHT: 3px">
<table border="1" width="100%" id="table1">
<tr>
<td>
<%
dim allid,ppp,id,totalnum
sql="select * from table order by id DESC"
set rs=server.createobject("adodb.recordset")
rs.open sql,conn,1,1
if not rs.eof then
do while not rs.eof
if allid="" then allid= rs("id") else allid= allid & ";" & rs("id")
rs.movenext
loop
else
If Rs.bof And Rs.EOF Then
Response.Write "还没有找到任何文章!"
End if
end if
rs.close
set rs=nothing

allid=";" allid
ppp=split(allid,";")
totalnum=ubound(ppp)
for id=1 to totalnum
Session("id")=Session("id") 1
creat(id)
response.write "正在生成znwl_"&id&".htm...<br>"
next
%>
 </td>
</tr>
</table>
</BODY>
</HTML>

<%
Function creat(id)
sql="SELECT * from table where id="&ID
set rs=conn.execute(sql)
dim name
name=rs("name")
conn.execute(sql)
rs.close
set rs=nothing
dim fso
dim znwl
dim art
dim fw
set fso=createobject("scripting.filesystemobject")
set znwl=fso.opentextfile(server.mappath("模板页"))
art=znwl.readall
znwl.close
%>

art=replace(art,"{$name$}",name)
set fw=fso.createtextfile(server.mappath("生成页存放位置及页面名称"),true)
fw.writeline art
fw.close
set fso=nothing
End Function




这种方法快,但是你的空间要不受限制!--智能网络

上面的方法仅供参考,并不是本人修改的最后版本,但是绝对好用.

wuyq11 2009-07-22
  • 打赏
  • 举报
回复
用进度条显示进度

线程执行方法到一定时间后休眠一定时间,再执行
qq904492758 2009-07-21
  • 打赏
  • 举报
回复
mark
wenblue7 2009-07-21
  • 打赏
  • 举报
回复
mark
up
messi_yang 2009-07-21
  • 打赏
  • 举报
回复
學習中····
ralpha08 2009-07-21
  • 打赏
  • 举报
回复
mark
zzs_happy 2009-07-21
  • 打赏
  • 举报
回复
有那么复杂吗?
传一个上去给你

--------------以下是生成静态网页的类------------
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.IO;
using System.Net;
using System.Text;

/// <summary>
/// change_htm 的摘要说明
/// 作用:转换任务任可访问url文件为静态网网页,后缀名为.htm
/// string url0 转换源文件地址
/// string c_Url0 保存新文件地址
/// return fileName 新文件访问url地址
/// </summary>
public class change_htm
{
public string change(string Url0,string c_Url0)
{
Encoding code = Encoding.GetEncoding("GB2312");
StreamReader sr = null;
StreamWriter sw = null;
string str = null;
//读取远程路径
WebRequest temp = WebRequest.Create(Url0.Trim());
WebResponse myTemp = temp.GetResponse();
try
{
//读取
sr = new StreamReader(myTemp.GetResponseStream(),code);
str = sr.ReadToEnd();
}
catch (Exception error)
{
throw error;
}
finally
{
sr.Close();
}
//将后缀名更改为.htm
string fileName = string.Empty;
string file_exe = string.Empty;
int l = Url0.Length;
while (Url0[l - 1].ToString() != ".")
{
file_exe = Url0[l - 1].ToString() + file_exe;
l--;
}
fileName = Url0.Replace("." + file_exe, ".htm");//替换
//写入
try
{
//string drt = Server.MapPath("");
//drt = drt + "\\" + fileName;
sw = new StreamWriter(c_Url0, false, code);
sw.Write(str);
sw.Flush();

}
catch (Exception ex)
{
throw ex;
}
finally
{
sw.Close();
}
return fileName;
}
}

-------------以下是调用以上类的生成静态网页的实例-------------
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.Net;
using System.Text;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//取根目录url
string drt = Server.MapPath("") + "//";
drt = drt + "index.htm";//保存地址
string url = TextBox1.Text.ToString();//源动态文件url地址(如:http://XXXX.XX.com/index.aspx)
//实例化转换类
change_htm c_1 = new change_htm();
string u = c_1.change(url, drt);
Response.Write("1.恭喜首页<a href=" + u + " target=_blank>" + u + "</a>已经生成!</br>");
}
catch (Exception error)
{
Response.Write(error.Message);
}
}
}
polic 2009-07-21
  • 打赏
  • 举报
回复
1楼的,先谢谢你的支持,不过你给的类太简单,我也有,只是在写循环批量生成的时候容易出错,只是因为线程跟不上循环速度。所以把原来的信息覆盖了。我想应该是这样的,只要有1秒钟的延时就不会出现这种问题。只是有点浪费时间,没有效率。而且如果数据量大的话,占用的系统资源太大了

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧