/// <summary> ///根據url獲取網站html圖片並保存 /// </summary> public void getimages(string url) { //創建一個request 同時可以配置requst其余屬性 System.Net.WebRequest imgRequst = System.Net.WebRequest.Create(url); //在這裡我是以流的方式保存圖片 System.Drawing.Image downImage = System.Drawing.Image.FromStream(imgRequst.GetResponse().GetResponseStream()); string dertory = string.Format(@"D:\測試圖片文件夾\{0}\", DateTime.Now.ToString("yyyy-MM-dd")); string fileName = string.Format("{0}.jpg", DateTime.Now.ToString("HHmmssffff")); if (!System.IO.Directory.Exists(dertory)) { System.IO.Directory.CreateDirectory(dertory); } downImage.Save(dertory + fileName); downImage.Dispose();//用完一定要釋放 }
/// <summary> ///根據url獲取網站html內容 /// </summary> /// <param name="url">url鏈接</param> /// <param name="msg">返回提示信息</param> public string GetHtmlContentByUrl(string url, out string msg) { string httpRequesttsdbTimeout = "30000";//超時值(以毫秒為單位)30S var htmlContent = string.Empty; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Timeout = int.Parse(httpRequesttsdbTimeout); var httpWebResponse =(HttpWebResponse)httpWebRequest.GetResponse(); var stream = httpWebResponse.GetResponseStream(); if (stream != null) { var streamReader = new StreamReader(stream, System.Text.Encoding.UTF8); htmlContent = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); stream.Close(); stream.Dispose(); } httpWebResponse.Close(); msg = ""; return htmlContent; } catch (Exception ex) { msg = "網絡連接失敗:" + ex.Message; return ""; } }