您的位置:首页 > 编程语言 > ASP

ASP.NET生成HTML静态页面

2010-08-21 16:20 816 查看
第一种方法:向服务器的动态页面发送请求,获取页面的html代码。这种方法缺点显而易见:速度慢。另外如果请求的动态页面有验证控件的话,返回的html页面却无法进行数据验证。

public static void getUrltoHtml(string Url,string Path)//Url为动态页面地址,Path为生成的静态页面

{

try

{

System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);

System.Net.WebResponse wResp =wReq.GetResponse();

System.IO.Stream respStream = wResp.GetResponseStream();

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('页面生成成功!');

}

catch(System.Exception ex)

{

   System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!-- alert('页面生成失败!"+ex.Message+"');

}

}

第二种方法:从文件读取模版,替换模版中的参数后输出文件,这种方法的生成速度上比第一种要快许多,而且模版内容可以用工具任意编辑主要代码:
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";//静态文件名

str = str.Replace("ShowArticle",strText); //模板页中的ShowArticle

str = str.Replace("biaoti",strText);

str = str.Replace("content",strContent);

str = str.Replace("author",strAuthor);

// 写文件

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;

}

}

第三种:利用xml或数组定义一个参数个数,循环更替模板页面中的模板。

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>

/// <param name="dirName">配置文件的路径名</param>

/// <param name="tag">配置文件中的标签名</param>

/// <returns>_replaceStr的长度</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">配置文件中的标签名</param>

/// <param name="dir">生成文件所在的文件夹的路径</param>

/// <param name="templateFile">模板文件的的路径</param>

/// <param name="param">要替换的字符串数组</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) 此方法用于读取配置文件,主要是获得要替换的字符串的个数,在本类同体现为一个字符串数组

public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param) 此方法用于生成静态页面 51.52行创建一个字符数组,数组长度为配置文件中的节点个数。55-58行读取模板文件,并用读到的模板文件的HTML代码生成一个StringBuilder对象。59-62行使用StringBuilderd对象的repalce()方法替换标记“$repalce[i]$"为真实的数据 config.xml。

<?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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: