ASP.NET生成静态网页的方法

来源:互联网 发布:域名防劫持 编辑:程序博客网 时间:2024/05/17 07:02
环境:Microsoft .NET Framework SDK v1.1
OS:Windows Server 2003 中文版

ASP.Net生成静态HTML页,在.Net中涉及此类操作的是System.IO
以下是程序代码
Code:
 1//生成HTML页
 2public static bool WriteFile(string strText,string strContent,string strAuthor)
 3{
 4string path = HttpContext.Current.Server.MapPath("/news/");
 5Encoding code = Encoding.GetEncoding("gb2312");
 6// 读取模板文件
 7string temp = HttpContext.Current.Server.MapPath("/news/text.html");
 8StreamReader sr=null;
 9StreamWriter sw=null;
10string str=""
11try
12{
13sr = new StreamReader(temp, code);
14str = sr.ReadToEnd(); // 读取文件
15}

16catch(Exception exp)
17{
18HttpContext.Current.Response.Write(exp.Message);
19HttpContext.Current.Response.End();
20sr.Close();
21}

22
23
24string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
25// 替换内容
26// 这时,模板文件已经读入到名称为str的变量中了
27str =str.Replace("ShowArticle",strText); //模板页中的ShowArticle
28str = str.Replace("biaoti",strText);
29str = str.Replace("content",strContent);
30str = str.Replace("author",strAuthor);
31// 写文件
32try
33{
34sw = new StreamWriter(path + htmlfilename , false, code);
35sw.Write(str);
36sw.Flush();
37}

38catch(Exception ex)
39{
40HttpContext.Current.Response.Write(ex.Message);
41HttpContext.Current.Response.End();
42}

43finally
44{
45sw.Close();
46}

47return true
此函数放在Conn.CS基类中了
在添加新闻的代码中引用 注:工程名为Hover
1if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString)))
2{
3Response.Write("添加成功");
4}

5else
6{
7Response.Write("生成HTML出错!");
8}
 
模板页Text.html代码
Code:
<!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> 
提示添加成功后会出以当前时间为文件名的html文件!上面只是把传递过来的几个参数直接写入了HTML文件中,在实际应用中需要先添加数据库,然后再写入HTML文件。 
原创粉丝点击