1. 程式人生 > >c# 下載遠端伺服器檔案

c# 下載遠端伺服器檔案

方法1:WebClient 讀取檔案流下載

 WebClient client = new WebClient();

            byte[] bytes = client.DownloadData(Url);

            HttpContext.Response.ContentType = "application/octet-stream";

            HttpContext.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(Url)));

            HttpContext.Response.AddHeader("Content-Length", bytes.Length.ToString());

            HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);

            HttpContext.Response.Flush();

            HttpContext.Response.Clear();

方法2:WebClient 直接下載到指定資料夾

            WebClient client = new WebClient();

            client.DownloadFile(Url, @"D:\"+HttpUtility.UrlEncode(Path.GetFileName(Url)));