在软件开发过程中有些页面是不经常变化的,此时如果重复从数据库中查询页面肯定会变慢,此时我们可以将该页面生成静态页面html的形式保存起来,下次加载的时候直接读取html页面
用流的形式读取页面生成静态页面,这种形式适用于静态化整个页面,下面用代码的形式记录学习的过程
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace ConsoleApplication1 { public abstract class ConvertPage { public bool flag; public string SavePath { set; get; } public string PagePath { set; get; } public abstract void PrintPage(); } public class ConvertToHtml : ConvertPage { /// <summary> /// 构造函数 /// </summary> /// <param name="pageUrl"></param> /// <param name="saveUrl"></param> public ConvertToHtml(string pageUrl, string saveUrl) { if (string.IsNullOrEmpty(pageUrl) || string.IsNullOrEmpty(saveUrl)) flag = false; base.PagePath = pageUrl; base.SavePath = saveUrl; } /// <summary> /// 获取文件保存的完整路径 /// </summary> /// <returns></returns> public string GetFileSavePath() { var index = PagePath.LastIndexOf("/") + 1; var name = PagePath.Substring(index, PagePath.Length - index); if (!name.EndsWith(".html")) name = string.Format("{0}.html", name); return string.Format("{0}/{1}", SavePath, name); } /// <summary> /// 生成静态页面的方法 /// </summary> public override void PrintPage() { if (flag == false) return; var filePath = GetFileSavePath(); //设置重新生成静态页面的间隔时间 if (File.Exists(filePath)) { DateTime dt = File.GetLastWriteTime(filePath); TimeSpan ts = dt - DateTime.Now; if (ts.TotalHours < 1) return; } else { FileStream file = File.Create(filePath); file.Close(); } string Result; WebRequest MyRequest = System.Net.HttpWebRequest.Create(PagePath); WebResponse MyResponse = MyRequest.GetResponse(); using (StreamReader MyReader = new StreamReader(MyResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))//这里根据网站的编码格式而定 { Result = MyReader.ReadToEnd(); MyReader.Close(); } FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("utf-8")); sw.WriteLine(Result); sw.Close(); fs.Close(); } } } 调用方式: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ConvertPage convert = new ConvertToHtml("http://www.linkin.net/job", @"D: est"); convert.PrintPage(); } } }
另外当需要读取页面内容时分为读取本地页面和读取线上页面
读取本地页面:
//FilePath为你的test.html的文件路径 public static string WriteFile(string FilePath) { Encoding code = Encoding.GetEncoding("utf-8"); // 读取模板文件 string temp = HttpContext.Current.Server.MapPath(FilePath); string str = ""; StreamReader sr = null; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 读取文件 } catch (Exception exp) { HttpContext.Current.Response.Write(exp.Message); HttpContext.Current.Response.End(); sr.Close(); } finally { sr.Close(); } return str; }
读取线上动态页面:
/// <summary> /// 读取动态页面HTML /// </summary> /// <param name="strUrl">动态页面地址</param> /// <returns></returns> public static string GetStringByUrl(string dynamicUrl) { WebRequest wrt = null; WebResponse wrse = null; try { wrt = WebRequest.Create(dynamicUrl); wrt.Timeout = 8000; wrse = wrt.GetResponse(); HttpWebResponse res = (HttpWebResponse)wrse; if (res.StatusCode == HttpStatusCode.OK) { } else if (res.StatusCode == HttpStatusCode.Redirect) { var redURL = res.ResponseUri.AbsoluteUri; } Stream strM = null; StreamReader SR = null; try { strM = wrse.GetResponseStream(); SR = new StreamReader(strM, code); string strallstrm = SR.ReadToEnd(); return strallstrm; } catch (Exception ex) { } finally { if (SR != null) { try { SR.Dispose(); SR.Close(); } finally { SR = null; } } if (strM != null) { try { strM.Dispose(); strM.Close(); } finally { strM = null; } } } return string.Empty; } catch { return ""; } finally { if (wrse != null) { try { wrse.Close();} finally { wrse = null; } } if (wrt != null) wrt = null; } }