第一种方法:直接转化一个页面的方法
public static bool CreateList(string url, string fna) { bool ok; //准备生成 string strHtml; StreamReader sr = null; //用来读取流 StreamWriter sw = null; //用来写文件 Encoding code = Encoding.GetEncoding("utf-8"); //定义编码 //构造web请求,发送请求,获取响应 WebRequest HttpWebRequest = null; WebResponse HttpWebResponse = null; HttpWebRequest = WebRequest.Create(url); HttpWebResponse = HttpWebRequest.GetResponse(); //获得流 sr = new StreamReader(HttpWebResponse.GetResponseStream(), code); strHtml = sr.ReadToEnd(); //写入文件 try { sw = new StreamWriter(fna, false, code); sw.Write(strHtml); sw.Flush(); ok = true; } catch (Exception ex) { HttpContext.Current.Response.Write("<p>写入文件出错:" + ex.Message); HttpContext.Current.Response.End(); ok = false; } finally { sw.Close(); } return ok; }
调用
第二种方法是用一个html模板生成一个html页面,模版里面有对应的标签,可以从数据库和别的地方取数据,填写这个标签,生成一个html页面,这个方法在很多新闻系统里有用到
private string CreateDetailPage(string EventID,string EventTitle, string EventBody, string EventTime, string EventStat) { //模版所有路径、模版文件名、生成的文件路径、生成的文件名 string path, temp, htmlfilepath,htmlfilename; path = Server.MapPath(""); temp = Server.MapPath("testhtml.htm"); htmlfilepath = path; htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + ".html"; //读模版 Encoding code = Encoding.GetEncoding("gb2312"); StreamReader sr = null; StreamWriter sw = null; string str = ""; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 读取文件 } catch (Exception exp) { HttpContext.Current.Response.Write("<p>读取文件出错:" + exp.Message); HttpContext.Current.Response.End(); sr.Close(); } // 替换内容 // 对应模版里的设置要修改 str = str.Replace("re_symbol_EventID", EventID); str = str.Replace("re_symbol_EventTitle", EventTitle); str = str.Replace("re_symbol_EventBody", EventBody); str = str.Replace("re_symbol_EventTime", EventTime); str = str.Replace("re_symbol_EventStat", EventStat); // 写文件 try { sw = new StreamWriter(htmlfilepath + "//" + htmlfilename, false, code); sw.Write(str); sw.Flush(); } catch (Exception ex) { HttpContext.Current.Response.Write("<p>写入文件出错:" + ex.Message); HttpContext.Current.Response.End(); } finally { sw.Close(); } return htmlfilename; }
调用的时候这样:
上个图吧