2013-06-21 296 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

謝謝,這工作 –