Skip to content

Instantly share code, notes, and snippets.

@ichadhr
Last active January 23, 2020 20:41
Show Gist options
  • Save ichadhr/ef87bc45dea31febe55dded2a572a5fa to your computer and use it in GitHub Desktop.
Save ichadhr/ef87bc45dea31febe55dded2a572a5fa to your computer and use it in GitHub Desktop.
C# File Download
public class FileDownload {
private volatile bool _completed;
public void DownloadFile(string address, string location) {
using(WebClient client = new WebClient()) {
Uri Uri = new Uri(address);
_completed = false;
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(Uri, location);
}
}
public bool DownloadCompleted {
get {
return _completed;
}
}
private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e) {
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string) e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
private void Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
if (e.Cancelled == true) {
Console.WriteLine("Download has been canceled.");
_completed = false;
} else if (e.Error != null) {
Console.WriteLine("Download error!");
_completed = false;
} else {
Console.WriteLine("Download completed!");
_completed = true;
}
}
}
// override DownloadFileAsync timeout to 10 second
public class WebClientWithTimeout: WebClient {
//10 secs default
public int Timeout {
get;
set;
} = 10000;
//for sync requests
protected override WebRequest GetWebRequest(Uri uri) {
var w = base.GetWebRequest(uri);
w.Timeout = Timeout; //10 seconds timeout
return w;
}
//the above will not work for async requests :(
//let's create a workaround by hiding the method
//and creating our own version of DownloadStringTaskAsync
public new async Task < string > DownloadStringTaskAsync(Uri address) {
var t = base.DownloadStringTaskAsync(address);
if (await Task.WhenAny(t, Task.Delay(Timeout)).ConfigureAwait(false) != t) //time out!
{
CancelAsync();
}
return await t.ConfigureAwait(false);
}
}

using

FileDownload Down = new FileDownload();
Down.DownloadFile(pathURL, pathSave);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment