用web request 下载档案

public void DownloadPanelPrice(string url, string fileName) { try { //如果要透過proxy且需要帳號密碼則需下列三行代碼 System.Net.WebProxy proxy = new System.Net.WebProxy("proxyIP:port"); proxy.Credentials = new System.Net.NetworkCredential("帳號", "密碼", "網域"); WebRequest.DefaultWebProxy = proxy; //url="http://localhost/Data/abc.xls"; WebRequest myWebRequest = WebRequest.Create(url); WebResponse myWebResponse = myWebRequest.GetResponse(); Stream receiveStream = myWebResponse.GetResponseStream(); //如果下載的檔案檔名固定則先刪除,再寫入,否則則視情況而定 File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.CreateNew); try { while (true) { //讀一個byte, 寫一個byte int i = receiveStream.ReadByte(); if (i == -1) { break; } fs.WriteByte(Convert.ToByte(i)); } } finally { fs.Close(); myWebResponse.Close(); } } catch (Exception ex) { throw ex; } finally { WebRequest.DefaultWebProxy = null; } }

你可能感兴趣的:(Web,.net)