第一種方法:向伺服器的動態網頁面發送請求,擷取頁面的html代碼。這種方法缺點顯而易見:速度慢。另外如果請求的動態網頁面有驗證控制項的話,返回的html頁面卻無法進行資料驗證。但這種方法寫起來比較簡單。主要代碼如下:
view plaincopy to clipboardprint?
#region//產生被請求URL靜態頁面
public static void getUrltoHtml(string Url,string Path)//Url為動態網頁面地址,Path為產生的靜態頁面
{
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
System.Net.WebResponse wResp =wReq.GetResponse();
// Get the response stream.
System.IO.Stream respStream = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
System.IO.StreamReader reader = new System.IO.StreamReader(respStream,System.Text.Encoding.GetEncoding("gb2312"));
string str=reader.ReadToEnd();
System.IO.StreamWriter sw=new System.IO.StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));
sw.Write(str);
sw.Flush();
sw.Close();
System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('頁面產生成功!');
// --></mce:script>");
}
catch(System.Exception ex)
{
System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('頁面產生失敗!"+ex.Message+"');
// --></mce:script>");
}
}
#endregion
#region//產生被請求URL靜態頁面
public static void getUrltoHtml(string Url,string Path)//Url為動態網頁面地址,Path為產生的靜態頁面
{
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
System.Net.WebResponse wResp =wReq.GetResponse();
// Get the response stream.
System.IO.Stream respStream = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
System.IO.StreamReader reader = new System.IO.StreamReader(respStream,System.Text.Encoding.GetEncoding("gb2312"));
string str=reader.ReadToEnd();
System.IO.StreamWriter sw=new System.IO.StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));
sw.Write(str);
sw.Flush();
sw.Close();
System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('頁面產生成功!');
// --></mce:script>");
}
catch(System.Exception ex)
{
System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('頁面產生失敗!"+ex.Message+"');
// --></mce:script>");
}
}
#endregion
第二種方法:從檔案讀模數版,替換模版中的參數後輸出檔案,這種方法的產生速度上比第一種要快許多,而且模版內容可以用工具任意編輯
主要代碼:
view plaincopy to clipboardprint?
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
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
第三種方法:如果產生的檔案數量比較多,第二種方法就要反覆讀模數版內容,這時可以用第三種方法——直接將你的模版寫在代碼中:
view plaincopy to clipboardprint?
/// <summary>
/// 自訂公用函數
/// </summary>
public class myfun
{
#region//定義模版頁
public static string SiteTemplate()
{
string str="";
str+="...";//模版頁html代碼
return str;
}
#endregion
public static bool WriteFile(string strText,string strContent,string strAuthor)
{
string path = HttpContext.Current.Server.MapPath("/test/");//檔案輸出目錄
Encoding code = Encoding.GetEncoding("gb2312");
StreamWriter sw=null;
string str=SiteTemplate();//讀模數版頁面html代碼
string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//靜態檔案名稱
// 替換內容
str = str.Replace("ShowArticle",strText);
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;
}
}
/// <summary>
/// 自訂公用函數
/// </summary>
public class myfun
{
#region//定義模版頁
public static string SiteTemplate()
{
string str="";
str+="...";//模版頁html代碼
return str;
}
#endregion
public static bool WriteFile(string strText,string strContent,string strAuthor)
{
string path = HttpContext.Current.Server.MapPath("/test/");//檔案輸出目錄
Encoding code = Encoding.GetEncoding("gb2312");
StreamWriter sw=null;
string str=SiteTemplate();//讀模數版頁面html代碼
string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//靜態檔案名稱
// 替換內容
str = str.Replace("ShowArticle",strText);
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;
}
}
三種方法比較起來產生速度由慢到快,易操作性則由簡到繁。還請根據實際情況選擇合適的方法。
[ 收 集 ] :
view plaincopy to clipboardprint?
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter html = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
base.Render(tw);
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("default.html"), false, System.Text.Encoding.Default);
sw.Write(html.ToString());
sw.Close();
tw.Close();
Response.Write(html.ToString());
}
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter html = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
base.Render(tw);
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("default.html"), false, System.Text.Encoding.Default);
sw.Write(html.ToString());
sw.Close();
tw.Close();
Response.Write(html.ToString());
}
view plaincopy to clipboardprint?
使用ASP.NET產生靜態頁面的方法有兩種,第一種是使用C#在後台寫入程式碼,第二種是讀模數板檔案,使用字串替換的方法。第一種方法編碼量大,而且維護比較困難。我重點講解第二種方法。第二種方法的基本思路是:使用DW之類的工具產生一個靜態頁面模板。讀取該模板檔案,然後對裡面的特殊標記使用真實的資料替換掉,並產生一個HTML檔案
請看代碼
1.C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
namespace htmlWeb
{
public class CreateHtm
{
private string fileName;
public String FileName
{
get { return fileName; }
}
/**//// <summary>
/// 讀取設定檔
/// </summary>
/// <param name="dirName">設定檔的路徑名</param>
/// <param name="tag">設定檔中的標籤名</param>
/// <returns>_replaceStr的長度</returns>
private int GetConfig(String dirName, String tag)
{
XmlDataDocument config = new XmlDataDocument();
try
{
config.Load(dirName);
}
catch (Exception ex)
{
throw ex;
}
XmlNodeList list = config.GetElementsByTagName(tag);
return list.Count;
}
/**//// <summary>
///產生HTML檔案
/// </summary>
/// <param name="configFileName">設定檔的路徑名</param>
/// <param name="configTag">設定檔中的標籤名</param>
/// <param name="dir">組建檔案所在的檔案夾的路徑</param>
/// <param name="templateFile">模板檔案的的路徑</param>
/// <param name="param">要替換的字串數組</param>
/// <returns>產生的檔案名稱</returns>
public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param)
{
fileName = null;
int count = GetConfig(configFileName, configTag);
String[] _replaceStr = new String[count];
try
{
FileStream tFile = File.Open(templateFile, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(tFile, Encoding.GetEncoding("gb2312"));
StringBuilder sb = new StringBuilder(reader.ReadToEnd());
reader.Close();
for (int i = 0; i < count; i++)
{
sb.Replace("$repalce[" + i + "]$", param[i]);
}
fileName = DateTime.Now.ToFileTime().ToString() + ".htm";
FileStream rFile = File.Create(dir+"/" + fileName);
StreamWriter writer = new StreamWriter(rFile, Encoding.GetEncoding("gb2312"));
writer.Write(sb.ToString());
writer.Flush();
writer.Close();
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteHtml(String dirName)
{
File.Delete(dirName);
}
}
}
private int GetConfig(String dirName, String tag) 此方法用於讀取設定檔(見後),主要是獲得要替換的字串的個數,在本類同體現為一個字串數組
public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param) 此方法用於產生靜態頁面
51.52行建立一個字元數組,數組長度為設定檔中的節點個數。55-58行讀模數板檔案,並用讀到的模板檔案的HTML代碼產生一個StringBuilder對象。59-62行使用StringBuilderd對象的repalce()方法替換標記“$repalce[i]$"為真實的資料
64行產生一個唯一的檔案名稱(防止覆蓋)66-70行把新的字串寫到檔案中。這樣就產生了一個靜態檔案了。
下面看一個使用的執行個體:
一個文章管理系統,利用這個類來產生靜態頁面。
首先,建立一個設定檔 config.xml.此檔案告訴使用者每個標記的含義。如下
<?xml version="1.0" encoding="utf-8" ?>
<htmlWeb version="1">
<config>
<article key="0" value="title"/>
<article key="1" value="author"/>
<article key="2" value="context"/>
<aritcle key="3" value="date"/>
</config>
</htmlWeb>
10這樣配置後,類會把標記數組0,1,2,3的位置分別替換為題目,作者,內容,發布日期。
看模板檔案
1<head>
2<title>模板檔案</title>
3</head>
4<body>
5<h1>這是一個簡單的HTML頁,朋友們可以根據自己的需要重新設計</h1>
6<li>標題:$replace[0]$</li>
7<li>作者:$replace[1]$</li>
8<li>內容:$repalce[2]$</li>
9<li>時間:$repalce[3]$</li>
10</body>使用方法:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11namespace UseT
12{
13 public class Test{
14
15 public void main(){
16 string[] param = new string[4];
17 param[0] = "測試模板";
18 param[1] = "農佳捷";
19 param[2] = "這是一個測試文章";
20 param[3] = "2007-10-30";
21
22 htmlWeb.CreateHtm cs = new htmlWeb.CreateHtm();
23 cs.MakeHtml("設定檔的路徑
24“, ”article“, ”組建檔案的路徑“, "模板檔案的路徑", param)
25
26 }
27 }
28}
29隻要把相應的參數修改為實際的值,就產生靜態檔案了。