对于网站特别是CMS系统中,生成静态页面是必不可少的,静态页面不用去和数据库打交道,可以提高页面的访问速度。生成静态页面的方法一般有
两种,一种是以模板的形式生成,第二种是直接根据URL来生成静态页面。
以模板形式生成
以模板形式生成的原理就是字符串替换,在.NET中已经提供了一个字符串替换的函数 Replace
用模板生成静态页面共分三步,和把大象放在冰箱里的步骤差不多
1.读取模板(把冰箱门打开)
2.替换字符串(把大象放在冰箱里)
3.保存替换后的字符串(把冰箱门关上)
我们建立一个 aaa.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> $title$</title>
</head>
<body>
<h2>$title$</h2>
<div>
内容:$content$
</div>
</body>
</html>
其中$title$ 和$content$ 就是我们要替换的字符串
string Path = Server.MapPath("template/aaa.htm");//得到模板的路径
Encoding code = Encoding.GetEncoding("gb2312");//用gb2312来编码
string str = string.Empty;
StreamReader sr = new StreamReader(Path, code);//把文件转换成流
str = sr.ReadToEnd();//把流从头读到尾
sr.Close();//关闭读流
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";//建立一个文件名
str = str.Replace("$title$", TextBox1.Text );//替换Title//
str = str.Replace("$content$", TextBox2.Text );//替换content
//生成静态文件
StreamWriter sw = new StreamWriter(Server.MapPath("html/") + fileName, false, code);
sw.Write(str);
sw.Flush();
sw.Close();
根据URL生成
根据URL生成就是直接读入要生成的URL并把返回的页面存成 html页面
Encoding code = Encoding.GetEncoding("gb2312");
string str = null;
//读取远程路径
WebRequest temp = WebRequest.Create(TextBox3.Text .Trim ());//这里我们用textBox3来填写url
WebResponse myTemp = temp.GetResponse();
StreamReader sr = new StreamReader(myTemp.GetResponseStream(), code);
//读取
str = sr.ReadToEnd();
sr.Close();
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
StreamWriter sw = new StreamWriter(Server.MapPath("html/") + fileName, false, code);
sw.Write(str);
sw.Flush();
sw.Close();
两种方法的原理都很简单,个人比较喜欢第一种方法,在cms系统中的生成静态页面大多也是采用第一种方法来做的,这样做可以提高页面定制的灵活性
联系客服