下面是通过C#调用模板页(test.html),动态的生成静态的HTML网页的源码。页面加载时调用方法清除不在最近某一时间断生成的网页。
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.IO; public partial class BuildPage : System.Web.UI.Page ... { private static string staticfilename = "" ; protected void Page_Load( object sender, EventArgs e) ... { if ( ! IsPostBack) ... { // 页面第一次加载时清除BuildPage文件夹下的文件 clearPic(); } } protected void BtnBuildHtml_Click( object sender, EventArgs e) ... { // 传入HTML页面的标题和内容,一般都是动态生成的。这里传入了一个固定的值
if (WriteFile( " 这是标题 " , " 这是内容 " )) ... { Response.Write( " 添加成功 " ); // 页面跳转到生成的HTML页面 Response.Redirect( " buildpage/ " + staticfilename); } else ... { Response.Write( " 生成HTML出错! " ); } } /**/ /// <summary> /// 删除不在这一分钟内产生的HTML文件 /// 应有相应的权限。需try /// </summary> private void clearPic() ... { string strAbsolutePath = HttpContext.Current.Server.MapPath( " BuildPage/ " ); string [] fileEntres = System.IO.Directory.GetFiles(strAbsolutePath); foreach ( string afile in fileEntres) ... { // 将文件的生成日期与系统日期相比,如果是当日以前生成的文件,删除它,这里精确到分钟,可根据需要设置临时文件保存的时间。 if (System.DateTime.Compare(System.IO.File.GetCreationTime(afile).AddMinutes( 1 ), System.DateTime.Now) < 0 ) ... { try ... { System.IO.File.Delete(afile); } catch (Exception) ... { } } } } /**/ /// <summary> /// 写入HTML文件,可根据需要修改 此方法的参数 /// </summary> /// <param name="strText"> 传入的标题 </param> /// <param name="strContent"> HTML的内容 </param> /// <returns></returns> private bool WriteFile( string strText, string strContent ) ... { string path = HttpContext.Current.Server.MapPath( " BuildPage/ " ); Encoding code = Encoding.GetEncoding( " gb2312 " ); // 读取模板文件 string temp = HttpContext.Current.Server.MapPath( " 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 " ; staticfilename = htmlfilename; // 替换内容 // 这时,模板文件已经读入到名称为str的变量中了 str = str.Replace( " Title " , strText); //替换 模板页中的Title str = str.Replace( " Content " , strContent); // 写入文件 try ... { string filename = path + htmlfilename; sw = new StreamWriter(filename, 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 ; } }
下面是模板页test.thml的HTML:
<! DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.0 Transitional//EN " > < HTML > < HEAD > < title > Title </ title > < body > content </ body > </ HTML >
如果这些代码给你带来了帮助,请留言。