添加一个类文件makefile:
#region 根据绝对url生成Htm页面
public bool makeUrlhtm(string pageUrl, string filePath, string fileName,string basepath)
{
string filePage = HttpContext.Current.Server.MapPath(filePath + fileName);
StreamWriter sw = null;
//获得静态html
try
{
if (!Directory.Exists(HttpContext.Current.Server.MapPath(filePath)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(filePath));
}
if (File.Exists(filePage))
{
File.Delete(filePage);
}
sw = new StreamWriter(filePage, false, Encoding.GetEncoding("GB2312"));
WebRequest wReq = WebRequest.Create(pageUrl);
WebResponse wResp = wReq.GetResponse();
Stream respStream = wResp.GetResponseStream();
StreamReader reader = new StreamReader(respStream, Encoding.GetEncoding("gb2312"));
string finalHtml = reader.ReadToEnd();
finalHtml = ClearInput(finalHtml);
//string basepath = "<base href='http://www.cupledu.com/StudyCenter/FsJobgrinds/' /><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
if (finalHtml.IndexOf(@"<head>")>0)
{
finalHtml.Insert(finalHtml.IndexOf(@"<head>")+6,basepath);
}
sw.Write(finalHtml);
//HttpContext.Current.Response.Write("<script language='JavaScript'>alert('生成成功!');</script>");
return true;
}
catch
{
//HttpContext.Current.Response.Write("<script language='JavaScript'>alert('生成失败!');</script>");
return false;//生成到出错
}
finally
{
sw.Flush();
sw.Close();
sw = null;
}
}
#endregion
#region ClearInput
public string ClearInput(string finalHtml)
{
string pattern = @"<input type=""hidden"" name=""__VIEWSTATE""[^>]*>";//清除hidden内容
string pattern1 = @"<input type=""hidden"" name=""__EVENTVALIDATION""[^>]*>";//清除hidden内容
string FormTargetBegin = @"<form name=[^>]*>";//清除Form
string FormTargetEnd = @"</form>";
//取得匹配值
string s = ((System.Text.RegularExpressions.Capture)(Regex.Match(finalHtml, pattern).Groups.SyncRoot)).Value;
finalHtml = Regex.Replace(finalHtml, pattern, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
finalHtml = Regex.Replace(finalHtml, pattern1, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
finalHtml = Regex.Replace(finalHtml, FormTargetBegin, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
finalHtml = Regex.Replace(finalHtml, FormTargetEnd, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
return finalHtml;
}
#endregion
调用:
makeFile function = new makeFile();
string url = "要下载的页面路径如www.baidu.com";
string severpath = Server.MapPath("~/");
string basepath = "<base href='http://www.cupledu.com/StudyCenter/FsJobgrinds/' /><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
function.makeUrlhtm(url, searpath, "zfindex.html", basepath);