直接读取网页写成静态页的几个方法
研究一下不用模板将页面写成静态页的方法,归纳以下3种。注意要引用2个命名空间:
using System.Net;
using System.IO;
using System.IO;
1.在服务器上指定aspx网页,生成html静态页1。
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("静态页1.html"),false,System.Text.Encoding.GetEncoding("GB2312"));
System.Web.HttpContext.Current.Server.Execute("t.aspx", sw);sw.Close();
System.Web.HttpContext.Current.Server.Execute("t.aspx", sw);sw.Close();
2.在服务器上执行aspx网页时在Page_Render事件里将本页面生成html静态页2。
protected override void Render(HtmlTextWriter writer){
System.IO.StringWriter html = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
base.Render(tw);
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("静态页2.htm"), false, System.Text.Encoding.Default);
sw.Write(html.ToString());
sw.Close();
tw.Close();
Response.Write(html.ToString());
}
System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
base.Render(tw);
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("静态页2.htm"), false, System.Text.Encoding.Default);
sw.Write(html.ToString());
sw.Close();
tw.Close();
Response.Write(html.ToString());
}
3.从指定连接获取源代码生成html静态页1。其实这应该算网页源代码获取方式了。
//获得指定链接的源代码
string PageUrl = "http://www.sohu.com";
WebRequest request = WebRequest.Create(PageUrl);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string ContentHtml = sr.ReadToEnd();
resStream.Close();
sr.Close();
string PageUrl = "http://www.sohu.com";
WebRequest request = WebRequest.Create(PageUrl);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string ContentHtml = sr.ReadToEnd();
resStream.Close();
sr.Close();
//写入文件
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("静态页生成方法3.htm"), false, System.Text.Encoding.Default);
sw.Write(ContentHtml);
sw.Close();
System.IO.StreamWriter sw;
sw = new System.IO.StreamWriter(Server.MapPath("静态页生成方法3.htm"), false, System.Text.Encoding.Default);
sw.Write(ContentHtml);
sw.Close();