環(huán)境:microsoft .net framework sdk v1.1 
os:windows server 2003 中文版
asp.net生成靜態(tài)html頁
在asp中實(shí)現(xiàn)的生成靜態(tài)頁用到的filesystemobject對(duì)象!
在.net中涉及此類操作的是system.io 
以下是程序代碼 注:此代碼非原創(chuàng)!參考別人代碼
//生成html頁
public static bool writefile(string strtext,string strcontent,string strauthor) 
{
string path = httpcontext.current.server.mappath("/news/");
encoding code = encoding.getencoding("gb2312");
// 讀取模板文件
string temp = httpcontext.current.server.mappath("/news/text.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";
// 替換內(nèi)容
// 這時(shí),模板文件已經(jīng)讀入到名稱為str的變量中了
str =str.replace("showarticle",strtext); //模板頁中的showarticle
str = str.replace("biaoti",strtext);
str = str.replace("content",strcontent);
str = str.replace("author",strauthor);
// 寫文件
try
{
sw = new streamwriter(path + htmlfilename , false, code);
sw.write(str);
sw.flush();
}
catch(exception ex)
{
httpcontext.current.response.write(ex.message);
httpcontext.current.response.end();
}
finally
{
sw.close();
}
return true;
此函數(shù)放在conn.cs基類中了
在添加新聞的代碼中引用 注:工程名為hover
if(hover.conn.writefilethis.title.text.tostring),this.content.text.tostring),this.author.text.tostring)))
{
response.write("添加成功");
}
else
{
response.write("生成html出錯(cuò)!");
}
-------------------------------------------------------------------------
模板頁text.html代碼
-------------------------------------------------------------------------
biaoti
content
author
------------------------------------------------------------------------
提示添加成功后會(huì)出以當(dāng)前時(shí)間為文件名的html文件!上面只是把傳遞過來的幾個(gè)參數(shù)直接寫入了html文件中,在實(shí)際應(yīng)用中需要先添加數(shù)據(jù)庫,然后再寫入html文件
而且需要把生成的文件名等寫入數(shù)庫以便以后調(diào)用等,此實(shí)例只是實(shí)現(xiàn)了根據(jù)提交過來參數(shù)替換模板中的相應(yīng)的字段! 需要完善的地方很多!哪位有高見,歡迎賜教!
posted on 2004-03-23 15:39 觀自在書院 閱讀(2111) 評(píng)論(5) 編輯 收藏 收藏至365key 所屬分類: dotnet 
feedback
# re: asp.net生成靜態(tài)html頁! 2004-05-17 09:37 kriss 
用html作為模板,替換其中變量只能實(shí)現(xiàn)一些簡單頁面 
有沒有辦法把我的aspx文件的運(yùn)行結(jié)果產(chǎn)生html呢? 
譬如我的首頁,內(nèi)容很復(fù)雜,用aspx寫的 
但由于用戶很多,為了提高速度,我每次更新數(shù)據(jù)后,重新產(chǎn)生首頁的html,但模板是aspx文件 回復(fù) 
# re: asp.net生成靜態(tài)html頁! 2004-05-18 18:03 檻上人 
這個(gè)效果用緩存可以實(shí)現(xiàn)的,比如你將頁面整體緩存3分種,和靜態(tài)頁面差不多了 回復(fù) 
# re: asp.net生成靜態(tài)html頁! 2004-06-01 13:36 kriss 
我找到我想用的方法了: 
using system.web.hosting; 
webhost host = (webhost)applicationhost.createapplicationhost( 
typeof(webhost), name, path); 
public void dorequest(string page, string query, textwriter writer) { 
httpruntime.processrequest(new simpleworkerrequest(page, query, writer)); 
} 
這樣我就可以直接把一個(gè)aspx文件產(chǎn)生html文件了 
filestream fs = file.open("default.htm"); 
host.dorequest("default.aspx",string.empty,fs); 回復(fù) 
新聞熱點(diǎn)
疑難解答
圖片精選