1 public void DownloadFile(string URL, string filename) 2 { 3 HttpWebRequest req = null; 4 HttpWebResponse rep = null; 5 Stream st = null; 6 Stream so = null; 7 try 8 { 9 req = (HttpWebRequest)WebRequest.Create(URL);//請求網路資源 10 11 req.UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36"; 12 13 rep = (HttpWebResponse)req.GetResponse();//返回Internet資源的響應 14 long totalBytes = rep.ContentLength;//獲取請求返回內容的長度 15 st = rep.GetResponseStream();//讀取伺服器的響應資源,以IO流的形式進行讀寫 16 so = new FileStream(filename, FileMode.Create); 17 long totalDownloadedByte = 0; 18 byte[] by = new byte[1024]; 19 int osize = st.Read(by, 0, (int)by.Length); 20 while (osize > 0) 21 { 22 totalDownloadedByte = osize + totalDownloadedByte; 23 so.Write(by, 0, osize); 24 osize = st.Read(by, 0, (int)by.Length);//讀取當前位元組流的總長度 25 } 26 so.Flush(); 27 } 28 catch (Exception ex) { ex.ToString(); } 29 finally 30 { 31 if (so != null) { so.Close(); so.Dispose(); } 32 if (st != null) { st.Close(); st.Dispose(); } 33 if (rep != null) { rep.Close(); rep.Dispose(); } 34 if (req != null) { req.Abort(); } 35 36 } 37 }