How to download a file from a website in C#
With the WebClient class:
using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
Use WebClient.DownloadFile
:
using (WebClient client = new WebClient())
{
client.DownloadFile("http://csharpindepth.com/Reviews.aspx",
@"c:\Users\Jon\Test\foo.txt");
}
You may need to know the status during the file download or use credentials before making the request.
Here is an example that covers these options:
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");
}
And the callback's functions implemented as follows:
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 notation: other possible option for handling the events
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) - We can do better
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) - Or
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!");
};