2013-06-21 137 views
0

好吧,我试着用WebClient的C#类到donwload从GitHub一个文件,但我总是损坏的文件..这是我的代码C#下载文件损坏

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)。 谢谢

+2

当您手动下载文件(无代码)时,该文件是否正常? – John

+2

是的,将尝试JustAnotherUser回答 –

+0

您应该使用'WebClient.DownloadFileAsync()'而不是'WebClient.DownloadFile()' –

回答

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

+0

谢谢,这工作 –