//構造web請求,發(fā)送請求,獲取響應
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頁面,模版里面有對應的標簽,可以從數(shù)據(jù)庫和別的地方取數(shù)據(jù),填寫這個標簽,生成一個html頁面,這個方法在很多新聞系統(tǒng)里有用到
我參考這里面的代碼寫的:http://www.webstudy8.com/web/net/201/065118272748882.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;
}
調用的時候這樣: