asp.net生成静态页面方法详细说明
最常用的方法从文件读取模版,替换模版中的参数后输出文件,这种方法的生成速度上比第一种要快许多,而且模版内容可以用工具任意编辑
主要代码:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using system.io;
using system.text;namespace xinxi
{
/// <summary>
/// createpage的摘要说明。
/// </summary>
// www.zzzyk.com
// 此类是生成静态网页的小程序public class create
{
public void createpage()
{
}
public static bool writefile(string strtext,string strcontent,string strauthor)
{
string path = httpcontext.current.server.mappath("/test/");//文件输出目录
encoding code = encoding.getencoding("gb2312");
// 读取模板文件
string temp = httpcontext.current.server.mappath("/template/test.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;
}
}
}
//原理是利用system.io中的类读写模板文件,然后用replace替换掉模板中的标签,写入静态html
下面看个实例
模板
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>showarticle</title>
<body>
biaoti
<br>
content<br>
author
</body>
</html>
biaoti
<br>
content<br>
author
</body>
</html>
c代码
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;
}
补充:asp.net教程,C语言