C#(asp.net)生成網站靜態化的方法
2017/6/25 11:49:44 獨占網絡 獨占觀點
講到網站建設,現在由于出于安全性問題,還有網站排名的問題考慮,所以許多的網站都使用靜態化來實現技術網站前臺網頁處理的,下面我們就進一下我們制作靜態化網頁的方法,實現網頁靜態化的方法,一般有兩種一種是直接通過,讀取動態網頁直接生成,一般是使用模板網頁替換的,我們今天就來講一下用模板網頁替換的方法。
1、靜態化網頁模板的代碼(index.html)
<div class="t_bg">
<div class="top">
<a href="/Contact/index.html">聯系我們</a>
</div>
</div>
<div class="head clearfix">
<div class="logo"><a href="/">
<img src="@company@" alt="@company@" /></a></div>
<div class="search">
<input class="showkeyword" type="text" placeholder="請輸入關鍵字">
<input class="searchbtn" type="submit" value="搜 索">
</div>
<div class="tel">
<span><em>熱線電話:</em> </span>
<b>@webtel@</b>
</div>
</div>
2、讀取網頁的模板頁(index.html)的代碼
/// <summary>
/// 根據文件的路徑讀取文件的信息
/// </summary>
/// <param name="filepath">文件的路徑</param>
/// <returns>返回文件的信息</returns>
public static string ReadFile(string filepath)
{
StringBuilder strhtml = new StringBuilder();
try
{
using (StreamReader reader = new StreamReader(filepath, System.Text.Encoding.GetEncoding("utf-8")))
{
while (reader.Peek() >= 0)
{
strhtml.Append(((char)reader.Read()).ToString());
}
}
}
catch { return ""; }
return strhtml.ToString();
}
3、替換標簽的代碼代碼
public static string returnWebConfig(string html)
{
html = html.Replace("@address@","深圳市");
html = html.Replace("@company@", "獨占網絡");
html = html.Replace("@webtel@", "公司電話");
}
4、寫入到新網頁的代碼
public bool CreateWriteFile(string strNewsFilePath, string verpath)
{
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;
}
通過上面四個方法就可以實現替換網頁生成新的靜態網頁。