ASP.NET產生HTML檔案的方法

來源:互聯網
上載者:User

一(轉貼)

此功能適用於後台資料庫功能不強的web網站,即大部分文本不是存放在資料庫的記錄中,而是放在html檔案或者xml檔案中,僅僅把索引放到資料庫中,如文章標題、類別、查詢關鍵字等。這樣適合於後台沒有諸如MS Sql Server這樣的資料庫支援的Web網站。

適用於新聞發布系統,比如sina、163等都是採用動態產生html頁面的。

適用於需動態定製頁面的程式。比如論壇、聊天室等。可以載入定製好的html頁面,來加強美觀。

思路

1. 利用如Dw-Mx這樣的工具產生html格式的模板,在需要添加格式的地方加入特殊標記(如$htmlformat$),動態組建檔案時利用代碼讀取此模板,然後獲得前台輸入的內容,添加到此模板的標記位置中,產生新檔案名稱後寫入磁碟,寫入後再向資料庫中寫入相關資料。

2. 使用後台代碼寫入程式碼Html檔案,可以使用HtmlTextWriter類來寫html檔案。

優點

1. 可以建立非常複雜的頁面,利用包含js檔案的方法,在js檔案內加入document.write()方法可以在所有頁面內加入如頁面頭,廣告等內容。

2. 靜態html檔案利用MS Windows2000的Index Server可以建立全文檢索搜尋引擎,利用asp.net可以以DataTable的方式得到搜尋結果。而Win2000的Index服務無法尋找xml檔案的內容。如果包括了資料庫搜尋與Index索引雙重尋找,那麼此搜尋功能將非常強大。

3. 節省伺服器的負荷,請求一個靜態html檔案比一個aspx檔案伺服器資源節省許多。

缺點

思路二: 如果用硬式編碼方式,工作量非常大,需要非常多的html代碼。調試困難。而且使用寫入程式碼產生的html樣式無法修改,如果網站更換樣式,那麼必須得重新編碼,給後期帶來巨大的工作量。

因此這裡採用的是第一種思路

示列代碼

1.定義(template.htm)html模板頁面

 

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

</head>

<body >

<table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000">

<tr>

<td width="100%" valign="middle" align="left">

<span style="color: $htmlformat[1];font-size: $htmlformat[2]">$htmlformat[3]</span>

</td>

</tr>

</table>

</body>

</html>

2.asp.net代碼:

//---------------------讀html模板頁面到stringbuilder對象裡----

string[] format=new string[4];//定義和htmlyem標記數目一致的數組

StringBuilder htmltext=new StringBuilder();

try

{

using (StreamReader sr = new StreamReader("存放模板頁面的路徑和頁面名"))

{

String line;

while ((line = sr.ReadLine()) != null)

{

htmltext.Append(line);

}

sr.Close();

}

}

catch

{

Response.Write("<Script>alert('讀取檔案錯誤')</Script>");

}

//---------------------給標記數組賦值------------

format[0]="background=/"bg.jpg/"";//背景圖片

format[1]= "#990099";//字型顏色

format[2]="150px";//字型大小

format[3]= "<marquee>產生的模板html頁面</marquee>";//文字說明

//----------替換htm裡的標記為你想加的內容

for(int i=0;i<4;i++)

{

htmltext.Replace("$htmlformat["+i+"]",format[i]);

}

//----------產生htm檔案------------------――

try

{

using(StreamWriter sw=new StreamWriter("存放路徑和頁面名",false,System.Text.Encoding.GetEncoding("GB2312")))

{

sw.WriteLine(htmltext);

sw.Flush();

sw.Close();

}

}

catch

{

Response.Write ("The file could not be wirte:");

}

小結

用此方法可以方便的產生html檔案。程式使用了是迴圈替換,因此對需替換大量元素的模板速度非常快。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2、我的執行個體:

void turnHtml()
  {

   string htmltext="";

   try

   {

    using (StreamReader sr = new StreamReader("F://OA//html//a.txt"))

    {

     string line;

     //用while 實現了把模板中的全部內容一行一行的全部讀出來
     while ((line = sr.ReadLine()) != null)

     {

      htmltext +=line;

     }
     hlink.Value=htmltext; //hlink為一個隱藏的input,這裡也可以是一個string。

     sr.Close();
     

    }
    

   }

   catch

   {

    Response.Write("<Script>alert('讀取檔案錯誤')</Script>");

   } 
     
   SqlConnection conn;
   conn=new SqlConnection(ConfigurationSettings.AppSettings["cnstr"]);
   conn.Open();
   SqlCommand cm=new SqlCommand("select top 5 wid,title,neirong from Tweb  order by wid desc",conn);
   SqlDataReader dr=cm.ExecuteReader();
   while(dr.Read())
   {
    htmltext=hlink.Value;

//---------------------給標記數組賦值------------ 
    string[] format=new string[2];
    format[0]=dr["title"].ToString();
    format[1]=dr["neirong"].ToString();
    for(int i=0;i<2;i++) //有幾個變數,就寫幾個數
    {
     htmltext =htmltext.Replace("$htmlformat["+i+"]",format[i]);

//----------替換htm裡的標記為你想加的內容
    }
    
    using(StreamWriter sw=new StreamWriter("F://OA//html//"+dr["wid"].ToString()+".html",false,System.Text.Encoding.GetEncoding("GB2312")))

    {

     sw.WriteLine(htmltext);

     sw.Flush();

     sw.Close();
    }
   }
   dr.Close();
   conn.Close();
   Label2.Text="HTML產生成功!";
   //ASPX頁還要有:validateRequest=false ,以防止第二點擊時出現錯誤

}

 

 

 

 

 

 

 

 

 

 

 

3、轉載:

<!--Main.Aspx-->
<%@ page language="C#" %>
<%@ import namespace=System.IO %>
<script runat="server">
protected override void OnInit (EventArgs e)
{
  int id;
  try
  {
    id = int.Parse (Request.QueryString["id"]);
  }
  catch
  {
    throw (new Exception ("頁面沒有指定id"));
  }
 
  string filename=Server.MapPath("statichtml_"+id+".html");
 
  //嘗試讀取已有檔案
  Stream s = GetFileStream (filename);
  if (s != null)//如果檔案存在並且讀取成功
  {
    using (s)
    {
      Stream2Stream (s, Response.OutputStream);
      Response.End ();
    }
  }
 
 
  //調用Main_Execute,並且擷取其輸出
  StringWriter sw = new StringWriter ();
  Server.Execute ("Main_Execute.aspx", sw);
 
  string content = sw.ToString ();
 
  //輸出到用戶端
  Response.Write(content);
  Response.Flush();
 
  //寫進檔案
 
  try
  {
    using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.Write))
    {
      using (StreamWriter streamwriter = new StreamWriter (fs, Response.ContentEncoding))
      {
        streamwriter.Write (content);
      }
    }
  }
  finally
  {
    //Response.End ();
  }
}
static public void Stream2Stream (Stream src, Stream dst)
{
  byte[] buf = new byte[4096];
  while (true)
  {
    int c = src.Read (buf, 0, buf.Length);
    if(c==0)
      return;
    dst.Write (buf, 0, c);
  }
}
public Stream GetFileStream(string filename)
{
  try
  {
    DateTime dt = File.GetLastWriteTime (filename);
    TimeSpan ts=dt - DateTime.Now;
    if(ts.TotalHours>1)
      return null;    //1小時後到期
    return new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  }
  catch
  {
    return null;
  }
}
</script>

<!--Main_Execute.aspx-->
<%@ page language="C#" %>
<html>
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>

ID:
<%=Request.QueryString["id"]%>

</body>
</html>

 

其中原理是這樣的.
Main_Execute.aspx是產生HTML的頁面.

現在用Main.aspx來對它進行緩衝.
過程如下:

首先根據頁面參數算出檔案名稱.(這個例子只根據Request.QueryString["id"]來算)
嘗試讀取緩衝的檔案.如果成功,那麼Response.End();
如果不成功:
使用Server.Execute來調用Main_Execute.aspx,並且擷取它的結果內容.
得到內容後,立刻輸出到用戶端.
最後把內容寫進檔案裡,提供給下一次做為緩衝度取.

 

 

最後:我也不知道是第一種方法好,還是第三種方法好。反正第一種好理解一些。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.