Reputation: 3318
Well, Im trying to donwload a file from GitHub using WebClient C# Class but I always get the file corrupted.. this is my code
using (var client = new WebClient())
{
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", @"C:/Users/Asus/Desktop/aa.zip");
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
}
static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage.ToString());
}
//////
public static void ReadFile()
{
WebClient client = new WebClient();
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", @"C:/Users/Asus/Desktop/aa.zip");
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
}
static void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Console.WriteLine("Finish");
}
static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage);
}
Now Im using that code and calling that function Reader.ReadFile(); , file downloads good but nothing is written in console (e.percentage) . Thanks
Upvotes: 0
Views: 4241
Reputation: 149
You are calling DownloadFile() before setting up your event handlers. The call to DownloadFile() will block your thread until the file has finished downloading, which means those event handlers will not be attached before your file has already downloaded.
You could switch the order around like so:
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", @"C:/Users/Asus/Desktop/aa.zip");
or you could use DownloadFileAsync() instead, which will not block your calling thread.
Upvotes: 1