0

好吧,我尝试使用 WebClient C# 类从 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)。谢谢

4

1 回答 1

1

您在设置事件处理程序之前调用 DownloadFile()。对 DownloadFile() 的调用将阻塞您的线程,直到文件完成下载,这意味着在您的文件下载之前不会附加这些事件处理程序。

您可以像这样切换顺序:

    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() 代替,这不会阻止您的调用线程。

于 2013-06-21T16:14:21.863 回答