本文转载自:http://www.cnblogs.com/yuanbao/archive/2008/01/06/1027985.html点击打开链接

一直以为动态生成静态页面不好做,昨天在网上找了下,其实很简单,思路大概是这样的, 

1:建立一个html页面模板,在这个页面中把你想要动态显示的地方用特殊的字符串表示(如 

$htmlstrstr$); 

2:在程序中用将这个html页面读到一个字符串变量如str; 

3:用字符串的resplace方法将在第一步中特殊字符替换成你想要的内容; 

4保存; 

OK,so easy,今天就用C#写了一个这样的类,用来处理动态生成html页面的,自认为还写的完 

整,刚接触.NET不久,望指教

注:此类中的代码不全是原创,部份代码参照网友的代码!

以下是转换类的代码

代码 
  1using System; 
  2using System.Text; 
  3using System.Web; 
  4using System.Configuration; 
  5using System.IO; 
  6namespace solucky 
  7{ 
  8    /**//// <summary> 
  9    /// AspxToHtml 的摘要说明。 
 10    /// 注:使用此类,你可以在web.config文件对模板类进行配置.如下 
 11    /**//*<appSettings> 
 12    <add key="templateFilePath" value="htmlmoudel.htm" /> 
 13    <add key="htmlFilePath" value="new/"></add> 
 14    <add key="ErrLogPath" value="aspxTohtml_log.txt"></add>     
 15    </appSettings>*/ 
 16    /**//// </summary> 
 17    public class AspxToHtml 
 18    { 
 19        /**//// <summary> 
 20        /// 模板文件中要替代的参数个数 
 21        /// </summary> 
 22        private int            _templateParamCount=0; 
 23        /**//// <summary> 
 24        /// 模板文件所在的路径 
 25        /// </summary> 
 26        private string        _templateFilePath  
       =ConfigurationSettings.AppSettings["templateFilePath"]; 
 27        /**//// <summary> 
 28        /// 转换后的html文件所存放的路径 
 29        /// </summary> 
 30        private string        _htmlFilePath  
           =ConfigurationSettings.AppSettings["htmlFilePath"]; 
 31         
 32        /**//// <summary> 
 33        /// 模板页页面编码 
 34        /// </summary> 
 35        private Encoding _templateHtmlCode    
         =Encoding.GetEncoding("gb2312"); 
 36 
 37        /**//// <summary> 
 38        /// 转换后的文件编码 
 39        /// </summary> 
 40        private Encoding _code = Encoding.GetEncoding("gb2312"); 
 41 
 42        /**//// <summary> 
 43        /// 转换后的html文件名 
 44        /// </summary> 
 45        private string  _convertedFilename=""; 
 46        /**//// <summary> 
 47        /// 模板文件中的参数 
 48        /// </summary> 
 49        private string[]    _templateFileparameter    ; 
 50         
 51        /**//// <summary> 
 52        /// aspx文件中的要代替HTML文件中的参数实际值 
 53        /// </summary> 
 54        private string[]    _aspxFileparameter; 
 55 
 56        private string _errlogPath = ConfigurationSettings.AppSettings["ErrLogPath"]; 
 57 
 58        属性#region 属性 
 59         
 60        /**//// <summary> 
 61        /// 模板文件中要替代的参数个数 
 62        /// </summary> 
 63        public int TemplateParamCount 
 64        { 
 65            get 
 66            { 
 67                return    this._templateParamCount; 
 68            } 
 69            set//分配参数个数时,同时为模板文件中的参数和aspx文件中的要代替 

HTML文件中的参数实际值这两个分配实际数组 
 70            { 
 71                if (value < 0)  
 72                    throw new ArgumentException(); 
 73 
 74                if(value>0)                 
 75                { 
 76                    this._templateParamCount=value; 
 77                    //模板文件中的参数                     
 78                    _templateFileparameter    = new string[value]; 
 79                    //aspx文件中的要代替HTML文件中的参数实际值 
 80                    _aspxFileparameter        = new string[value]; 
 81                } 
 82                else 
 83                    this._templateParamCount=0; 
 84            } 
 85        } 
 86         
 87        /**//// <summary> 
 88        /// 模板文件所在的路径 
 89        ///  
 90        /// </summary> 
 91        public string TemplateFilePath 
 92        { 
 93            get{    return this._templateFilePath;} 
 94            set{    this._templateFilePath=value;} 
 95        } 
 96        /**//// <summary> 
 97        /// 转换后的html文件所存放的路径 
 98        /// </summary> 
 99        public string HtmlFilePath 

100        { 

101            get{    return this._htmlFilePath;} 

102            set{    this._htmlFilePath=value;} 

103        } 

104 

105        /**//// <summary> 

106        /// html模板文件编码 

107        /// </summary> 

108        public Encoding TemplateHtmlCode 

109        { 

110            get{    return this._templateHtmlCode;} 

111            set{    this._templateHtmlCode=Encoding.GetEncoding(value.ToString());} 

112        } 

113        /**//// <summary> 

114        /// 编码 

115        /// </summary> 

116        public Encoding Code 

117        { 

118            get{    return this._code;} 

119            set{    this._code=Encoding.GetEncoding(value.ToString());} 

120        } 

121        /**//// <summary> 

122        /// 错误文件所在路径 

123        /// </summary> 

124        public string ErrLogPath 

125        { 

126            get{ 

127                if(!(this._errlogPath==null)) 

128                    return this._errlogPath; 

129                else 

130                    return "aspxTohtml_log.txt"; 

131            } 

132            set{this._errlogPath=value;} 

133        } 

134 

135         

136        #endregion 

137         

138        操作#region 操作 

139 

140        /**//// <summary> 

141        /// 获取转换后的html文件所在相对文件路径 

142        /// 如:如果HtmlFilePath="/news/" 

143        /// 转换后的html文件名为200505050505.html 

144        /// 则返回的值为/news/200505050505.html 

145        /// </summary> 

146        /// <remarks>如果在未调用StartConvert方法之前调用此属性则返回 

null</remarks> 

147        public string HtmlFileVirtualPath 

148        { 

149            get 

150            {     

151                if(!(this._convertedFilename=="")) 

152                    return    this.HtmlFilePath+this._convertedFilename; 

153                else 

154                    return null; 

155            } 

156        } 

157 

158        /**//// <summary> 

159        /// 为HTML页面参数数组付值 

160        /// </summary> 

161        /// <param name="param"></param> 

162        public void    setTemplateFileparameter(string[] param) 

163        { 

164            try 

165            { 

166                if(param.Length==this.TemplateParamCount) 

167                    this._templateFileparameter=param; 

168                //else//与原定义的个数不等 

169                    // 

170            } 

171            catch(System.Exception    ex) 

172            { 

173                WriteErrFile(ex); 

174            } 

175        } 

176        /**//// <summary> 

177        /// 为aspx文件中将要替换html文件中的参数数组付值 

178        /// </summary> 

179        /// <param name="param"></param> 

180        public void setAspxFileparameter(string[] param) 

181        { 

182            try 

183            { 

184                if(param.Length==this.TemplateParamCount) 

185                    this._aspxFileparameter=param; 

186                //else//与原定义的个数不等 

187                // 

188            } 

189            catch(System.Exception    ex) 

190            { 

191            WriteErrFile(ex); 

192            } 

193        } 

194        /**//// <summary> 

195        /// 开始进行aspxTohtml转换 

196        /// </summary> 

197        /// <returns>返回值为成功创建后的文件名称</returns> 

198        /// <remarks>在调用此方法之前必需确定已调用setTemplateFileparameter 和 

setAspxFileparameter方法进行相应的付值操作</remarks> 

199        public string StartConvert() 

200        { 

201            if(this._templateFileparameter.Length==this._aspxFileparameter.Length) 

202            { 

203                return writeFile(); 

204            } 

205            else{ 

206                return null; 

207            } 

208        } 

209        /**//// <summary> 

210        /// 开始进行aspxTohtml转换 

211        /// </summary> 

212        /// <param name="htmlparam">html模板页中的所有参数数组</param> 

213        /// <param name="aspxparam">aspx页面中要代替html模板页中参数值数组 

</param> 

214        /// <returns>返回值为成功创建后的文件名称</returns> 

215        public string StartConvert(string[] htmlparam,string[] aspxparam) 

216        { 

217            //先调用setTemplateFileparameter 和setAspxFileparameter方法,进行付值 

操作 

218            setTemplateFileparameter(htmlparam); 

219            setAspxFileparameter(aspxparam); 

220            // 

221            string fn=this.StartConvert(); 

222            // 

223            _convertedFilename=fn; 

224            // 

225            return fn; 

226        } 

227         

228        /**//// <summary> 

229        /// 用时间加随机数生成一个文件名 

230        /// </summary> 

231        /// <returns></returns> 

232        private string getfilename() 

233        { 

234            //用时间加随机数生成一个文件名 

235            System.Threading.Thread.Sleep(50); 

236            string yearStr = System.DateTime.Now.Year.ToString(); 

237            string monthStr = string.Format("{0:0#}",System.DateTime.Now.Month); 

238            string dayStr = string.Format("{0:0#}",System.DateTime.Now.Day);  

239            string hourStr = string.Format("{0:0#}",System.DateTime.Now.Hour); 

240            string minuteStr = string.Format("{0:0#}",System.DateTime.Now.Minute); 

241            string secondStr = string.Format("{0:0#}",System.DateTime.Now.Second); 

242 string millisecondStr = string.Format("{0:000#}",System.DateTime.Now.Millisecond);   
                

243            System.Random rd = new System.Random(); 

244            return yearStr + monthStr + dayStr + hourStr + minuteStr + secondStr +  

millisecondStr + string.Format("{0:0000#}",rd.Next(100))+".html"; 

245            //return DateTime.Now.ToString("yyyyMMddHHmmss")+".html"; 

246        } 

247        /**//// <summary> 

248        /// 进行转换处理 

249        /// </summary> 

250        /// <returns>返回以时间命名的文件名</returns> 

251        private string writeFile() 

252        { 

253             

254            // 读取模板文件 

255            string temp = HttpContext.Current.Server.MapPath(this.TemplateFilePath); 

256            StreamReader sr=null;             

257            string str="";  

258            try 

259            { 

260                sr = new StreamReader(temp, this.TemplateHtmlCode); 

261                str = sr.ReadToEnd(); // 读取文件 

262            } 

263            catch(Exception ex) 

264            { 

265                //HttpContext.Current.Response.Write(exp.Message); 

266                //HttpContext.Current.Response.End();         

267                WriteErrFile(ex); 

268            } 

269            finally 

270            { 

271                sr.Close(); 

272            }             

273            // 替换内容 

274            // 这时,模板文件已经读入到名称为str的变量中了 

275            for(int i=0;i<this.TemplateParamCount;i++) 

276            { 

277                str =str.Replace(this._templateFileparameter[i],this._aspxFileparameter[i]);  

278            }         

279 

280            return savefile(str);  

281        } 

282 

283        /**//// <summary> 

284        ///  

285        /// </summary> 

286        /// <param name="str"></param> 

287        /// <returns></returns> 

288 

289        private string savefile(string str) 

290        { 

291            // 写文件 

292            StreamWriter sw=null; 

293            try 

294            { 

295                 

296                string path = HttpContext.Current.Server.MapPath(this.HtmlFilePath); 

297                //html文件名称     

298                string htmlfilename=getfilename(); 

299                sw = new StreamWriter(path + htmlfilename , false, this.Code); 

300                sw.Write(str); 

301                sw.Flush(); 

302                return htmlfilename;  

303            } 

304            catch(Exception ex) 

305            {                 

306                WriteErrFile(ex); 

307            } 

308            finally 

309            { 

310                sw.Close(); 

311            } 

312            return ""; 

313        } 

314 

315        /**//// <summary> 

316        /// 传入URL返回网页的html代码 

317        /// </summary> 

318        /// <param name="Url">URL</param> 

319        /// <returns></returns> 

320        public string getUrltoHtml(string Url) 

321        {             

322            try 

323            { 

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

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

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

327                System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312")); 

328                return  savefile(reader.ReadToEnd()); 

329 

330            } 

331            catch(System.Exception ex) 

332            { 

333                WriteErrFile(ex); 

334            } 

335            return ""; 

336        } 

337        #endregion 

338 

339 

340        构造#region 构造         

341         

342        public AspxToHtml() 

343        { 

344            // 

345            // TODO: 在此处添加构造函数逻辑 

346            //             

347        } 

348 

349        private void settemplateParamCount(int templateParamCount) 

350        { 

351            if (templateParamCount>0) 

352                this.TemplateParamCount=templateParamCount; 

353        } 

354        /**//// <summary> 

355        /// 提供欲代替的参数个数 

356        /// </summary> 

357        /// <param name="templateParamCount"></param> 

358        public AspxToHtml(int templateParamCount) 

359        {     

360            settemplateParamCount(templateParamCount); 

361             

362        } 

363        /**//// <summary> 

364        ///  

365        /// </summary> 

366        /// <param name="templateParamCount">html模板页中的参数个数</param> 

367        /// <param name="htmlFilePath">生成的html文件所存放的文件夹路径</param> 

368        /// <param name="templateFilePath">html模板页路径</param> 

369        public AspxToHtml(int templateParamCount,string htmlFilePath,string  

templateFilePath) 

370        { 

371            settemplateParamCount(templateParamCount); 

372            this.HtmlFilePath        =    htmlFilePath; 

373            this.TemplateFilePath    =    templateFilePath; 

374             

375        } 

376        #endregion 

377 

378        #region 

379         

380        /**//// <summary> 

381        /// 把错误写入文件方法#region 把错误写入文件方法 

382        /// </summary> 

383        /// <param name="ee"></param> 

384        private  void WriteErrFile(Exception ee) 

385        { 

386             

387            FileStream fs1 = new  

FileStream(HttpContext.Current.Server.MapPath(ErrLogPath), System.IO.FileMode.Append); 

388            StreamWriter sw1 = new StreamWriter(fs1); 

389            sw1.WriteLine("**************************************************"); 

390            sw1.WriteLine("错误日期:" + System.DateTime.Now); 

391            sw1.WriteLine("错误描述:" + ee.Message); 

392            sw1.WriteLine("错误名称:" + ee.Source); 

393            sw1.WriteLine("详细:" + ee.ToString()); 

394            sw1.WriteLine("*************************************************"); 

395            sw1.Close(); 

396        } 

397        #endregion 

398    }

根据html页面模板动态生成html页面(c#类)的更多相关文章

  1. Javascript动态生成的页面信息爬取和openpyxl包FAQ小记

    最近,笔者在使用Requests模拟浏览器发送Post请求时,发现程序返回的html与浏览器F12观察到的略有不同,经过观察返回的response.text,cookies确认有效,因为我们可以看到返 ...

  2. HtmlUnit爬取Ajax动态生成的页面内容

    HtmlUnit说白了就是一个浏览器,这个浏览器是用Java写的无界面的浏览器,正因为其没有界面,因此执行的速度还是可以滴. HtmlUnit提供了一系列的API,这些API可以干的功能比较多,如表单 ...

  3. 根据数据库内容动态生成html页面

    之前使用了很多方法,但是都很复杂. 项目里包括了数据库的管理页面,对数据库进行修改(新增,插入,删除)等之后,在另一个页面使用. 使用时采用按下相应label弹出所有信息的方法,以html的形式将数据 ...

  4. htmlunit爬虫工具使用--模拟浏览器发送请求,获取JS动态生成的页面内容

    Htmlunit是一款模拟浏览抓取页面内容的java框架,具有js解析引擎(rhino),可以解析页面的js脚本,得到完整的页面内容,特殊适合于这种非完整页面的站点抓取. 下载地址: https:// ...

  5. 通过js根据后台数据动态生成一个页面

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportSelField ...

  6. phantomjs 截取twitter的网页(动态生成的页面)

    // This example shows how to render pages that perform AJAX calls// upon page load.//// Instead of w ...

  7. 分享一个动态生成RDLC报表的类

    在实际工作中,当需要进行大批量查询和生成报表的时候,可以使用我写的类. 特点: 无需报表设计器.无需为报表设置数据集 只需要传入查询结果就可以全自动生成报表,传入的对象为Dynamic(目前支持Dat ...

  8. java抓取动态生成的网页

    最近在做项目的时候有一个需求:从网页面抓取数据,要求是首先抓取整个网页的html源码(后期更新要使用到).刚开始一看这个简单,然后就稀里哗啦的敲起了代码(在这之前使用过Hadoop平台的分布式爬虫框架 ...

  9. [转]把动态页面.aspx 生成静态页面.html

    本文转自:http://blog.csdn.net/csb5201314/article/details/5391688 如果要把主页Index.aspx 生成静态页面 Index.html后输出会提 ...

随机推荐

  1. vue学习中遇到的onchange、push、splice、forEach方法使用

    最近在做vue的练习,发现有些js中的基础知识掌握的不牢,记录一下: 1.onchange事件:是在域的内容改变时发生,单选框与复选框改变后触发的事件. 2.push方法:向数组的末尾添加一个或多个元 ...

  2. Active Directory 域服务对象

    局域网计算机控制中心 可以在DC上控制所有局域网资源(计算机 .用户.设备) 大中型企业管理必备. 最后,它还可以让开发人员集成LDAP身份认证,使用域账号登录应用. 也就是说,此企业的所有系统,都可 ...

  3. What is mobile platform?

    高屋建瓴 From Up to Down Outside into inside The Internet Of Things. http://wenku.baidu.com/view/5cdc026 ...

  4. centos7 gearmand-1.1.15打包rpm

    wget https://github.com/gearman/gearmand/releases/download/1.1.15/gearmand-1.1.15.tar.gz -O /root/rp ...

  5. check_mk 之 Configuration variables

    Basic settings #check_parameters This is a configuration list assigning specific check parameters to ...

  6. HTML:::before和::after伪元素的用法

    随笔 - 366  文章 - 0  评论 - 392 ::before和::after伪元素的用法   一.介绍 css3为了区分伪类和伪元素,伪元素采用双冒号写法. 常见伪类——:hover,:li ...

  7. Active Directory域服务备份

    此篇介绍如何通过Windows Server Backup工具备份Active Directory域服务 AD 域系统状态 在域控制器上,系统状态通常包括以下内容,但所包含的数据实际上取决于服务器上安 ...

  8. Lucene学习入门——核心类API

    本文讲解Lucene中,创建索引.搜索等常用到的类API 搜索操作比索引操作重要的多,因为索引文件只被创建一次,却要被搜索多次. 索引过程的核心类: 执行简单的索引过程需要如下几个类:IndexWri ...

  9. RC4 in TLS is Broken: Now What?

    https://community.qualys.com/blogs/securitylabs/2013/03/19/rc4-in-tls-is-broken-now-what RC4 has lon ...

  10. Oracle编程入门经典 第12章 事务处理和并发控制

    目录 12.1          什么是事务处理... 1 12.2          事务处理控制语句... 1 12.2.1       COMMIT处理... 2 12.2.2       RO ...