ASP.Net生成静态HTML页(转)

来源:互联网 发布:movist for mac 官网 编辑:程序博客网 时间:2024/06/06 18:51
 public static bool WriteFile(string strText,string strContent,string strAuthor) 
 2   {
 3    string path = HttpContext.Current.Server.MapPath("/news/");
 4    Encoding code = Encoding.GetEncoding("gb2312");
 5    // 读取模板文件
 6    string temp = HttpContext.Current.Server.MapPath("/news/text.html");
 7    StreamReader sr=null;
 8    StreamWriter sw=null;
 9    string str="";  
10    try
11    {
12     sr = new StreamReader(temp, code);
13     str = sr.ReadToEnd(); // 读取文件
14    }
15    catch(Exception exp)
16    {
17     HttpContext.Current.Response.Write(exp.Message);
18     HttpContext.Current.Response.End();
19     sr.Close();
20    }
21   
22    
23    string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
24    // 替换内容
25    // 这时,模板文件已经读入到名称为str的变量中了
26    str =str.Replace("ShowArticle",strText); //模板页中的ShowArticle
27    str = str.Replace("biaoti",strText);
28    str = str.Replace("content",strContent);
29    str = str.Replace("author",strAuthor);
30    // 写文件
31    try
32    {
33     sw = new StreamWriter(path + htmlfilename , false, code);
34     sw.Write(str);
35     sw.Flush();
36    }
37    catch(Exception ex)
38    {
39     HttpContext.Current.Response.Write(ex.Message);
40     HttpContext.Current.Response.End();
41    }
42    finally
43    {
44     sw.Close();
45    }
46    return true;
47 
48 此函数放在Conn.CS基类中了
49 在添加新闻的代码中引用 注:工程名为Hover
50  
51     if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString)))
52     {
53      Response.Write("添加成功");
54     }
55     else
56     {
57      Response.Write("生成HTML出错!");
58     }
59 
模板页Text.html代码
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
 2 <HTML>
 3  <HEAD>
 4   <title>ShowArticle</title>
 5   
 6  <body>
 7  biaoti
 8  <br>
 9  content<br>
10  author
11  </body>
12 </HTML>
13