以前感覺http下載還是很玄乎的東西,隨著了解的深入才發(fā)現(xiàn),HTTP下載實際就是一個web請求,只是請求的內(nèi)容有可能會大一些,需要多讀取幾次,把請求請求到的內(nèi)容保存成文件,就實現(xiàn)了通過HTTP下載文件的整個過程。實際應用中肯定還有很多其它的需求,比如斷點續(xù)傳、多線程下載大文件等待,有時間再慢慢整理這些。 /// <summary> /// 下載文件 /// </summary> /// <param name="downLoadUrl">文件的url路徑</param> /// <param name="saveFullName">需要保存在本地的路徑(包含文件名)</param> /// <returns></returns> public bool DownloadFile(string downLoadUrl, string saveFullName) { bool flagDown = false; System.Net.HttpWebRequest httpWebRequest = null; try { //根據(jù)url獲取遠程文件流 httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream sr = httpWebResponse.GetResponseStream();
//創(chuàng)建本地文件寫入流 System.IO.Stream sw = new System.IO.FileStream(saveFullName, System.IO.FileMode.Create);
long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = sr.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; sw.Write(by, 0, osize); osize = sr.Read(by, 0, (int)by.Length); } System.Threading.Thread.Sleep(100); flagDown = true; sw.Close(); sr.Close(); } catch (System.Exception) { if (httpWebRequest != null) httpWebRequest.Abort(); } return flagDown; }
|