通過ASP.NET產生靜態檔案的文章網上有好多文章,而本站也有不少的相關文章教程,通常ASP.NET產生靜態檔案的做法是使用檔案流讀模數板內容,之後替換模板內容中相關關鍵字,再產生靜態檔案。本文的做法另類一點,通過URL來產生靜態檔案,下面來看下是如何?吧。
建立一個TestWeb.aspx檔案,這個檔案後台.cs的代碼做法步驟如下:
第1步:先引用如下命令空間
using System;
using System.Net;
using System.IO;
using System.Text;
第2步:建立擷取遠程URL並組建檔案的方法與檔案夾不存在則自動建立方法
擷取遠程URL並組建檔案的代碼:
C# Code [http://www.xueit.com]
/// <summary> /// 產生網頁檔案 /// </summary> /// <param name="url">遠程URL</param> /// <param name="filename">組建檔案名路徑</param> /// <param name="pagecode">目標URL頁面編碼</param> protected void DownUrltoFile(string url, string filename, string pagecode) { try { //編碼 Encoding encode = Encoding.GetEncoding(pagecode); //請求URL HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //設定逾時(10秒) req.Timeout = 10000; this.NotFolderIsCreate(filename); //擷取Response HttpWebResponse rep = (HttpWebResponse)req.GetResponse(); //建立StreamReader與StreamWriter檔案流對象 StreamReader sr = new StreamReader(rep.GetResponseStream(),encode); StreamWriter sw = new StreamWriter(Server.MapPath(filename), false,encode); //寫入內容 sw.Write(sr.ReadToEnd()); //清理當前緩衝區,並將緩衝寫入檔案 sw.Flush(); //釋放相關對象資源 sw.Close(); sw.Dispose(); sr.Close(); sr.Dispose(); Response.Write("組建檔案" filename "成功"); } catch (Exception ex) { Response.Write("組建檔案" filename "失敗,原因:" ex.Message); } }
以上代碼關鍵知識點,通過HttpWebRequest、HttpWebResponse請求擷取遠程URL資料,之後使用StreamReader、StreamWriter檔案流讀寫資料寫入檔案,注意還有編碼Encoding。
檔案夾不存在則自動建立的代碼:
C# Code [http://www.xueit.com]
/// <summary> /// 檔案夾不存在則建立 /// </summary> /// <param name="filename">檔案名稱所在路徑</param> protected void NotFolderIsCreate(string filename) { string fileAtDir = Server.MapPath(Path.GetDirectoryName(filename)); if (!Directory.Exists(fileAtDir)) Directory.CreateDirectory(fileAtDir); }
下面我們看下如何調用組建檔案。
在Page_Load中調用DownUrltoFile()方法,以擷取百度首頁產生靜態檔案
C# Code [http://www.xueit.com]
protected void Page_Load(object sender, EventArgs e) { //調用方法 this.DownUrltoFile("http://www.baidu.com", "html/baidu.htm", "GB2312"); }
因為百度首頁是Gb2312編碼,所以上面的調用方法輸入GB2312。我們來看下產生的:
運行1
產生後檔案
開啟產生的靜態檔案
怎麼樣,不錯吧。
有了這個方法,可以很簡單的通過動態檔案URL來產生靜態檔案了,比如:
新聞資訊表article有一個欄位htmlFile,儲存資訊檔案名稱的,內容如html/news/20091224-001.html,在後台添加儲存文章後,調用方法:
Code [http://www.xueit.com]
DownUrltoFile("http://www.xueit.com/show.aspx?pid=1", "html/news/20091224-001.html", "GB2312");
其中URL:http://www.xueit.com/show.aspx?pid=1 是動態顯示文章,html/news/20091224-001.html是表欄位htmlFile預先儲存的檔案名稱,這樣就可以產生靜態檔案了。
以上的做法是不使用模板來產生靜態檔案的方法,只是換個思路來做,有好建議可以上我的站 一起來交流下。