是否可以从Windows应用程序表单中的网站下载文件并将其放入某个目录?
使用WebClient类:
using System.Net; //... WebClient Client = new WebClient (); Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
用途WebClient.DownloadFile
:
using (WebClient client = new WebClient()) { client.DownloadFile("http://csharpindepth.com/Reviews.aspx", @"c:\Users\Jon\Test\foo.txt"); }
您可能需要在下载文件期间了解状态,或在发出请求之前使用凭据.
以下是一个涵盖这些选项的示例:
Uri ur = new Uri("http://remotehost.do/images/img.jpg"); using (WebClient client = new WebClient()) { //client.Credentials = new NetworkCredential("username", "password"); String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword")); client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}"; client.DownloadProgressChanged += WebClientDownloadProgressChanged; client.DownloadDataCompleted += WebClientDownloadCompleted; client.DownloadFileAsync(ur, @"C:\path\newImage.jpg"); }
回调函数的实现如下:
void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); // updating the UI Dispatcher.Invoke(() => { progressBar.Value = e.ProgressPercentage; }); } void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e) { Console.WriteLine("Download finished!"); }
(Ver 2) - Lambda表示法:处理事件的其他可能选项
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) { Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); // updating the UI Dispatcher.Invoke(() => { progressBar.Value = e.ProgressPercentage; }); }); client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){ Console.WriteLine("Download finished!"); });
(Ver 3) - 我们可以做得更好
client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => { Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); // updating the UI Dispatcher.Invoke(() => { progressBar.Value = e.ProgressPercentage; }); }; client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { Console.WriteLine("Download finished!"); };
(Ver 4) - 或者
client.DownloadProgressChanged += (o, e) => { Console.WriteLine($"Download status: {e.ProgressPercentage}%."); // updating the UI Dispatcher.Invoke(() => { progressBar.Value = e.ProgressPercentage; }); }; client.DownloadDataCompleted += (o, e) => { Console.WriteLine("Download finished!"); };
当然,你只需要使用一个HttpWebRequest
.
一旦你的HttpWebRequest
设置,您可以响应流保存到一个文件中StreamWriter
(无论是BinaryWriter
,还是TextWriter
取决于媒体类型.),你有你的硬盘驱动器上的文件.
编辑:忘了WebClient
.只要你只需要GET
用来检索你的文件,那就行得很好.如果网站要求您提供POST
信息,您将不得不使用HttpWebRequest
,所以我将离开我的答案.