第一種是模版替換:
環境: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>
biaoti
<br>
content<br>
author
</body>
</HTML>
提示加入成功後會出以當前時間為檔名的html檔!上面只是把傳遞過來的幾個參數直接寫入了HTML檔,
在實際應用中需要先新增資料庫,然後再寫入HTML檔.
第二種:
WebRequest存取aspx頁面,然後取得Response串流,得到的就是html
private void button1_Click(object sender, System.EventArgs e)
{
textBox1.Text=this.GetUrlValue(" http://YourUrl ");
}
//使用HttpWebRequest取得URL的回傳值
public string GetUrlValue(string url)
{
System.Net.WebRequest HttpWebRequest=System.Net.WebRequest.Create(url);
System.Net.WebResponse HttpWebResponse =HttpWebRequest.GetResponse();
System.IO.StreamReader sr=new System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
return sr.ReadToEnd();
}