I’m trying to make a class with a downloader that I can keep reusing so I don’t get a enormous code after a while. But I can’t seem to return the client_DownloadProgressChanged event. This is the code I have right now:
public static string progress;
public static int percent;
static WebClient client = new WebClient();
/// <summary>
/// Download a file from the internet
/// </summary>
/// <param name="url">The URL to download from</param>
/// <param name="path">The path to save to don't forget the / at the end</param>
/// <param name="filename">The filename of the file that is going to be download</param>
public static string DownloadFile(string url, string path, string filename)
{
try
{
Thread bgThread = new Thread(() =>
{
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri(url), path + filename);
});
bgThread.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
};
return progress;
}
static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString(CultureInfo.InvariantCulture));
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString(CultureInfo.InvariantCulture));
double percentage = bytesIn/totalBytes*100;
progress = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive;
percent = int.Parse(Math.Truncate(percentage).ToString(CultureInfo.InvariantCulture));
while (client.IsBusy)
{
return progress;
}
}
First of all your
Threadis redundant. If you read msdn article aboutDownloadFileAsyncyou will see:Having that in mind you method gets simpler:
I’ve added two method arguments that will be called when progress is made or when download finishes.
To call this method use: