五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > ASP.NET生成靜態(tài)頁(yè)面的代碼

ASP.NET生成靜態(tài)頁(yè)面的代碼

文章來(lái)源:365jz.com     點(diǎn)擊數(shù):294    更新時(shí)間:2011-04-13 09:50   參與評(píng)論

第一種方法:向服務(wù)器的動(dòng)態(tài)頁(yè)面發(fā)送請(qǐng)求,獲取頁(yè)面的html代碼。這種方法缺點(diǎn)顯而易見(jiàn):速度慢。另外如果請(qǐng)求的動(dòng)態(tài)頁(yè)面有驗(yàn)證控件的話,返回的html頁(yè)面卻無(wú)法進(jìn)行數(shù)據(jù)驗(yàn)證。但這種方法寫(xiě)起來(lái)比較簡(jiǎn)單。主要代碼如下:

view plaincopy to clipboardprint?
#region//生成被請(qǐng)求URL靜態(tài)頁(yè)面   
public static void getUrltoHtml(string Url,string Path)//Url為動(dòng)態(tài)頁(yè)面地址,Path為生成的靜態(tài)頁(yè)面   
{   
 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('頁(yè)面生成成功!');   
// --></mce:script>");   
 }   
 catch(System.Exception ex)   
 {   
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--   
alert('頁(yè)面生成失敗!"+ex.Message+"');   
// --></mce:script>");   
 }   
}  
#endregion  
#region//生成被請(qǐng)求URL靜態(tài)頁(yè)面
public static void getUrltoHtml(string Url,string Path)//Url為動(dòng)態(tài)頁(yè)面地址,Path為生成的靜態(tài)頁(yè)面
{
 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('頁(yè)面生成成功!');
// --></mce:script>");
 }
 catch(System.Exception ex)
 {
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('頁(yè)面生成失敗!"+ex.Message+"');
// --></mce:script>");
 }
}
#endregion

第二種方法:從文件讀取模版,替換模版中的參數(shù)后輸出文件,這種方法的生成速度上比第一種要快許多,而且模版內(nèi)容可以用工具任意編輯
主要代碼:

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";//靜態(tài)文件名   
  
  // 替換內(nèi)容   
  // 這時(shí),模板文件已經(jīng)讀入到名稱為str的變量中了   
  str = str.Replace("ShowArticle",strText); //模板頁(yè)中的ShowArticle   
  str = str.Replace("biaoti",strText);   
  str = str.Replace("content",strContent);   
  str = str.Replace("author",strAuthor);   
  // 寫(xiě)文件   
  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中的類讀寫(xiě)模板文件,然后用Replace替換掉模板中的標(biāo)簽,寫(xiě)入靜態(tài)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";//靜態(tài)文件名

   // 替換內(nèi)容
   // 這時(shí),模板文件已經(jīng)讀入到名稱為str的變量中了
   str = str.Replace("ShowArticle",strText); //模板頁(yè)中的ShowArticle
   str = str.Replace("biaoti",strText);
   str = str.Replace("content",strContent);
   str = str.Replace("author",strAuthor);
   // 寫(xiě)文件
   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中的類讀寫(xiě)模板文件,然后用Replace替換掉模板中的標(biāo)簽,寫(xiě)入靜態(tài)html

第三種方法:如果生成的文件數(shù)量比較多,第二種方法就要反復(fù)讀取模版內(nèi)容,這時(shí)可以用第三種方法——直接將你的模版寫(xiě)在代碼中:

view plaincopy to clipboardprint?
/// <summary>   
/// 自定義公共函數(shù)   
/// </summary>   
public class myfun   
{  
 
 #region//定義模版頁(yè)   
 public static string SiteTemplate()   
 {   
  string str="";   
  str+="...";//模版頁(yè)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();//讀取模版頁(yè)面html代碼    
  
  string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//靜態(tài)文件名   
  
  // 替換內(nèi)容   
  str = str.Replace("ShowArticle",strText);   
  str = str.Replace("biaoti",strText);   
  str = str.Replace("content",strContent);   
  str = str.Replace("author",strAuthor);   
  // 寫(xiě)文件   
  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>
 /// 自定義公共函數(shù)
 /// </summary>
 public class myfun
 {

  #region//定義模版頁(yè)
  public static string SiteTemplate()
  {
   string str="";
   str+="...";//模版頁(yè)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();//讀取模版頁(yè)面html代碼

   string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//靜態(tài)文件名

   // 替換內(nèi)容
   str = str.Replace("ShowArticle",strText);
   str = str.Replace("biaoti",strText);
   str = str.Replace("content",strContent);
   str = str.Replace("author",strAuthor);
   // 寫(xiě)文件
   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;
  }
 }

三種方法比較起來(lái)生成速度由慢到快,易操作性則由簡(jiǎn)到繁。還請(qǐng)根據(jù)實(shí)際情況選擇合適的方法。

[  收  集  ] :

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生成靜態(tài)頁(yè)面的方法有兩種,第一種是使用C#在后臺(tái)硬編碼,第二種是讀取模板文件,使用字符串替換的方法。第一種方法編碼量大,而且維護(hù)比較困難。我重點(diǎn)講解第二種方法。第二種方法的基本思路是:使用DW之類的工具生成一個(gè)靜態(tài)頁(yè)面模板。讀取該模板文件,然后對(duì)里面的特殊標(biāo)記使用真實(shí)的數(shù)據(jù)替換掉,并生成一個(gè)HTML文件   
請(qǐng)看代碼   
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">配置文件中的標(biāo)簽名</param>   
       /// <returns>_replaceStr的長(zhǎng)度</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">配置文件中的標(biāo)簽名</param>   
        /// <param name="dir">生成文件所在的文件夾的路徑</param>   
       /// <param name="templateFile">模板文件的的路徑</param>   
        /// <param name="param">要替換的字符串?dāng)?shù)組</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) 此方法用于讀取配置文件(見(jiàn)后),主要是獲得要替換的字符串的個(gè)數(shù),在本類同體現(xiàn)為一個(gè)字符串?dāng)?shù)組   
    public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param) 此方法用于生成靜態(tài)頁(yè)面   
51.52行創(chuàng)建一個(gè)字符數(shù)組,數(shù)組長(zhǎng)度為配置文件中的節(jié)點(diǎn)個(gè)數(shù)。55-58行讀取模板文件,并用讀到的模板文件的HTML代碼生成一個(gè)StringBuilder對(duì)象。59-62行使用StringBuilderd對(duì)象的repalce()方法替換標(biāo)記“$repalce[i]$"為真實(shí)的數(shù)據(jù)   
64行生成一個(gè)唯一的文件名(防止覆蓋)66-70行把新的字符串寫(xiě)到文件中。這樣就生成了一個(gè)靜態(tài)文件了。   
下面看一個(gè)使用的實(shí)例:   
一個(gè)文章管理系統(tǒng),利用這個(gè)類來(lái)生成靜態(tài)頁(yè)面。   
首先,建立一個(gè)配置文件 config.xml.此文件告訴使用者每個(gè)標(biāo)記的含義。如下   
<?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這樣配置后,類會(huì)把標(biāo)記數(shù)組0,1,2,3的位置分別替換為題目,作者,內(nèi)容,發(fā)布日期。   
看模板文件   
 1<head>   
 2<title>模板文件</title>   
 3</head>   
 4<body>   
 5<h1>這是一個(gè)簡(jiǎn)單的HTML頁(yè),朋友們可以根據(jù)自己的需要重新設(shè)計(jì)</h1>   
 6<li>標(biāo)題:$replace[0]$</li>   
 7<li>作者:$replace[1]$</li>   
 8<li>內(nèi)容:$repalce[2]$</li>   
 9<li>時(shí)間:$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] = "測(cè)試模板";   
18     param[1] = "農(nóng)佳捷";   
19     param[2] = "這是一個(gè)測(cè)試文章";   
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只要把相應(yīng)的參數(shù)修改為實(shí)際的值,就生成靜態(tài)文件了。 

如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答!! 點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (294人查看,0條評(píng)論)
請(qǐng)自覺(jué)遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)