標籤:
一般用.net產生靜態化網頁方法有兩種,一般是通過瀏覽器去觸發動態.aspx檔案來達到解析網頁,然後再產生網頁,這種方法我們不用(因為這種方法需要浪費比較大的伺服器效能,而且速度比較慢,一秒大概只能產生10個網頁左右),所以我們今天要講的是第二種方法,寫一個網頁模板,然後再用.net去解析標籤,然後以完成這一個產生網頁靜態化功能(獨佔網路(http://www.sz886.com)-深圳網站建設-http://www.sz886.com技術人員測試過1秒可以產生100多個網頁,效能非常好而且穩定,如果在開啟多線程的情況,使用者體驗效果也非常好。)
?
首先我們產生網頁化網頁需要用到的技術就有I/O流的檔案讀寫,然後我們再會用到Regex去解析標籤,最多我們再用多線程去保證穩定還有速度。
首先我們建立一個叫duzhan.html(主檔案),還有一個top.html(頭部檔案)
我們在頭部檔案裡面寫資訊如下:
這是網頁的頭部檔案,頭部檔案來源了深圳市獨佔網路科技有限公司(http://www.sz886.com)
然後我們寫入duzhan.html(主檔案)的代碼是
<!doctype html>
<html>
<head>
</head>
//這是要解析的標頭檔,剛才是上面的我們寫的Top.html檔案
<!--include file="Top.html" /-->
//這是一個迴圈的解析標籤,我們下面會用到,我們這裡先寫在這裡
<!--list table="1" typeid="1" num="10" where=" 1=1 " order="sortid asc,id asc" -->
//這是一個判斷的標籤,我們這裡也是先寫在這裡,下面會講到
<!--if testbase="@[email protected]" testvalue="1" testmodel="=" -->
<li><a href="@[email protected]"><img rel="@[email protected]" src="@[email protected]"/></a></li>
<!--else-->
<li><a href="@[email protected]"><img rel="@[email protected]" src=""/></a></li>
<!--/if-->
<!--/list-->
</body>
</html>
現在我們已經把兩個網頁的模板寫好了,接下面我們就是要解析好我們寫的標籤,然後去產生它。
首先我們建一個CreateFile.cs檔案來放置讀寫檔案的方法。
//這是一個建立新靜態頁面資訊,newsStrWebInfo是一個傳入我們傳入的參數(用於替換原有的資訊)
public static string CreateSingleFile(string strModeFilePath)
{
//建立一個讀檔案資訊的檔案流
StreamReader strReader = null;
//尋找出模組檔案在伺服器裡面的路徑,這裡不用Server.MapPath,在多線程的時候會有問題
string FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + strModeFilePath;
//怎樣一個編號為Utf-8的資訊
Encoding code = Encoding.GetEncoding("utf-8");
//建立一個strAllInfo字串用於存放我們讀取的資訊
string strAllInfo = string.Empty;
try
{
//得到一個讀取的檔案流,檔案路徑為FilePath,編碼為code
strReader = new StreamReader(FilePath, code);
//讀取檔案流裡面的全部資訊然後存放在strAllInfo裡面去
strAllInfo = strReader.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
} finally
{ //關閉讀取檔案流
strReader.Close();
}
return strAllInfo;
}
然後我們再寫一個入的方法。
public bool CreateWriteFile(string strNewsFilePath, string strFileinfo)
{
bool flag = false;
//建立一個寫檔案資訊的檔案流
StreamWriter strWrite = null;
//怎樣一個編號為Utf-8的資訊
Encoding code = Encoding.GetEncoding("utf-8");
try
{ //建立一個寫入檔案流
strWrite = new StreamWriter(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + strNewsFilePath, false, code);
//將剛才記取到的資訊寫入到檔案流裡面去
strWrite.Write(strFileinfo);
//建立成功就true
flag = true;
}catch (Exception ex)
{
throw ex;
} finally
{ strWrite.Flush();
//關閉檔案流
strWrite.Close();
}
return flag;
}
上面的定義了讀取的模板還有產生模板的方法了,我們接下來就是建立一個解析標籤的方法。
我們就建立一個 DuZhanTag.cs檔案
我們建立一個產生網頁的方法
public void createDefault(string htmlpath, string filename)
{
//將我們剛才寫的duzhan.html檔案路徑寫進去然後讀取到資訊
string html = CreateFile.CreateSingleFile(htmlpath);
//如果讀取的資訊沒有讀取到資訊我們就返回回去。
if (string.IsNullOrEmpty(html))
{ return; }
//解析我們的標籤,這個方法我們在下面定義。
html=CreateIncludeHtml(strAllInfo);
//組建檔案
new CreateFile().CreateWriteFile(filename, html);
}
由於網頁放不下,所以我們把下面的方法寫在 .net快速產生靜態網頁的方法二 http://www.sz886.com/zhishi/112110.html
.net快速產生靜態網頁的方法一