ASP.NET页面生成HTML

网上看到很多人问NET生成HTML的相关技术,我以前也曾为这个问题伤脑筋很久,网上的很多是模版替换

字符的方法来实现,在实际的应用中,那样的方法根本就没有用。其实生成HTML的原理就是读取已经存在

的网站的HTML代码,再保存为其他文件,命名为****.htm或****.html。我自己写了一个类,使用很简单

,比较容易懂,也希望能给大家一点启示。

类名为schtml.cs

 

 

复制代码
 1using System; 
 2using System.Data; 
 3using System.Configuration; 
 4using System.Web; 
 5using System.Web.Security; 
 6using System.Web.UI; 
 7using System.Web.UI.HtmlControls; 
 8using System.Web.UI.WebControls; 
 9using System.Web.UI.WebControls.WebParts; 
10using System.Web.Hosting; 
11using System.IO; 
12using System.Text; 
13using System.Net; 
14
15/// <summary> 
16///schtml 的摘要说明 
17/// </summary> 

18public class schtml 
19
20    public schtml() 
21    
22        // 
23        //TODO: 在此处添加构造函数逻辑 
24        // 
25    }
 
26
27
28    //生成html 
29    public void creathtml(string url,string path) 
30    
31        Encoding code = Encoding.GetEncoding("utf-8"); 
32        StreamReader sr = null
33        StreamWriter sw = null
34        string str = null
35         
36        //读取远程路径 
37        WebRequest temp = WebRequest.Create("http://" + HttpContext.Current.Request.Url.Host.ToString() + url); 
38        WebResponse myTemp = temp.GetResponse(); 
39        sr = new StreamReader(myTemp.GetResponseStream(), code); 
40        //读取 
41        try 
42        
43            sr = new StreamReader(myTemp.GetResponseStream(), code); 
44            str = sr.ReadToEnd(); 
45
46        }
 
47        catch (Exception ex) 
48        
49            throw ex; 
50        }
 
51        finally 
52        
53            sr.Close(); 
54        }
 
55
56        //写入 
57        try 
58        
59            sw = new StreamWriter(path, false, code); 
60            sw.Write(str); 
61            sw.Flush(); 
62
63        }
 
64        catch (Exception ex) 
65        
66            throw ex; 
67        }
 
68        finally 
69        
70            sw.Close(); 
71
72        }
 
73
74    }
 
75}

76
复制代码

 

使用方法也很简单

1 schtml html1 = new schtml(); 
2  html1.creathtml("/product/default.aspx", Server.MapPath("http://www.cnblogs.com/product/"+ "index.htm");

 

 

html1.creathtml的两个参数说明一下:

前面一个是页面路径/product/default.aspx

后面一个Server.MapPath("http://www.cnblogs.com/product/") + "index.htm",是指要把生成的文件保存在哪个文件夹,此处是保存在product目录下,文件名为index.html

 

 

可以相互交流相互学习

 

 

作者:joylee

出处:https://www.cnblogs.com/joylee/archive/2008/10/15/1311846.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   IT米粉  阅读(626)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题