Html生成模块:WriteHtml.cs
1 using System.Collections.Generic; 2 using System.IO; 3 using System.Text; 4 5 namespace System 6 { 7 ///8 /// Html 9 /// 10 public class Html11 {12 ///13 /// 生成Html14 /// 15 /// 模版文件16 /// 生成的文件目录17 /// 生成的文件名18 /// 字典19 /// 异常消息20 ///21 public bool Create(string template, string path, string htmlname, Dictionary dic, ref string message)22 {23 bool result = false;24 string templatepath = System.Web.HttpContext.Current.Server.MapPath(template);25 string htmlpath = System.Web.HttpContext.Current.Server.MapPath(path);26 string htmlnamepath = Path.Combine(htmlpath, htmlname);27 Encoding encode = Encoding.UTF8;28 StringBuilder html = new StringBuilder();29 30 try31 {32 //读取模版33 html.Append(File.ReadAllText(templatepath, encode));34 }35 catch (FileNotFoundException ex)36 {37 message = ex.Message;38 return false;39 }40 41 foreach (KeyValuePair d in dic)42 {43 //替换数据44 html.Replace(45 string.Format("${0}$", d.Key),46 d.Value);47 }48 49 try50 {51 //写入html文件52 if (!Directory.Exists(htmlpath))53 Directory.CreateDirectory(htmlpath);54 File.WriteAllText(htmlnamepath, html.ToString(), encode);55 result = true;56 }57 catch (IOException ex)58 {59 message = ex.Message;60 return false;61 }62 63 return result;64 }65 }66 }
模版文件:/Template/a.html
1 2 3 4 5$title$ 6 7 8 $content$ 9 $author$10 11
调用网页:test.ashx
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 5 namespace Wycz 6 { 7 ///8 /// test 的摘要说明 9 /// 10 public class test : IHttpHandler11 {12 13 public void ProcessRequest(HttpContext context)14 {15 //context.Response.ContentType = "text/plain";16 //context.Response.Write("Hello World");17 string template = "/Template/a.html";18 string path = "/test/";19 string htmlname = "a.html";20 Dictionarydic = new Dictionary ();21 Html h = new Html();22 string message = string.Empty;23 24 dic.Add("title", "动态生成html");25 dic.Add("content", "测试内容");26 dic.Add("author", "P.R");27 28 if (!h.Create(template, path, htmlname, dic, ref message))29 {30 context.Response.Write("出错啦: ");31 context.Response.Write(message);32 context.Response.End();33 }34 35 context.Response.Redirect(path + htmlname);36 }37 38 public bool IsReusable39 {40 get41 {42 return false;43 }44 }45 }46 }
效果图: