1. 程式人生 > >asp.net 下載網頁原始碼

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();