asp教程.net產生靜態頁面代碼
private static void createfile(string userid, string filename, string htmlcode)
{
filename += ".html";
string localpath = "e:/www.111cn.net/sun/sundecorativesystem/users/" + userid;
if (!directory.exists(localpath))
{
directory.createdirectory(localpath);
}
localpath += "/" + filename;
if (file.exists(localpath))
{
file.delete(localpath);
}
filestream fs = new filestream(localpath, filemode.createnew);
streamwriter sw = new streamwriter(fs);
sw.autoflush = true;
htmlcode = htmlcode.replace("+", """);
sw.write(htmlcode);
sw.flush();
sw.close();
fs.close();
}
//下面來看一款完整理的asp.net教程產生html代碼執行個體吧。
環境:microsoft .net framework sdk v1.1
os:windows server 2003 中文版
asp.net產生靜態html頁
在asp中實現的產生靜態頁用到的filesystemobject對象!
在.net中涉及此類操作的是system.io
以下是程式碼 注:此代碼非原創!參考別人代碼
//產生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";
// 替換內容
// 這時,模板檔案已經讀入到名稱為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;
此函數放在conn.cs基類中了
在添加新聞的代碼中引用 註:工程名為hover
if(hover.conn.writefilethis.title.text.tostring),this.content.text.tostring),this.author.text.tostring)))
{
response.write("添加成功");
}
else
{
response.write("產生html出錯!");
}
-------------------------------------------------------------------------
模板頁text.html代碼
-------------------------------------------------------------------------
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>showarticle</title>
<body>
biaoti
<br>
content<br>
author
</body>
</html>