好吧,我试图使用WebClient C#Class从GitHub下载文件,但我总是让文件损坏..这是我的代码
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);
}
现在我正在使用该代码并调用该函数Reader.ReadFile(); ,文件下载良好,但没有任何内容写入控制台(e.percentage)。 感谢
答案 0 :(得分:1)
在设置事件处理程序之前,您正在调用DownloadFile()。对FileFile()的调用将阻塞您的线程,直到文件下载完毕,这意味着在您的文件已经下载之前,这些事件处理程序将不会被附加。
您可以像这样切换订单:
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");
或者你可以使用DownloadFileAsync(),它不会阻止你的调用线程。