asp.net 下载网页源代码

//指定下载的文件名
string fileName = "网页源代码.txt";//客户端保存的文件名
//指定下载的url地址:http://www.baidu.com
string url = "http://www.baidu.com";
WebClient client = new WebClient();用于传递url资源的方法
client.Encoding = Encoding.UTF8;
byte[] html = client.DownloadData(url);
string strPath = MapPath("~/html");定义储存路径
if(!Directory.Exists(strPath))
{
    Directory.CreateDirectory(strPath);
}
string savePath = Path.Combine(strPath,"html.txt");//下载文件的详细地址
using(FileStream fsSave = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
    fsSave .Write(html, 0, html.Length);
}
//义字符流的形式下载文件
 FileStream fs = new FileStream(savePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();

猜你喜欢

转载自blog.csdn.net/qq_31975127/article/details/58042909