2012-09-27 92 views
0

我使用以下代碼從C#windows應用程序中的特定網址下載文件。下載文件

private void button1_Click(object sender, EventArgs e) 
{ 
    string url = @"DOWNLOADLINK"; 
    WebClient web = new WebClient(); 
    web.DownloadFileCompleted += new AsyncCompletedEventHandler(web_DownloadFileCompleted); 
    web.DownloadFile(new Uri(url), @"F:\a"); 
} 

void web_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
{ 
    MessageBox.Show("The file has been downloaded"); 
} 

但它也有這一行的錯誤:web.DownloadFile(new Uri(url), @"F:\a");

它說:一個Web客戶端請求期間發生

例外。

+1

您是否有權訪問「F:\ a」文件夾?此外,你需要指定一個文件,它應該是類似於「F:\ a.txt」 –

+0

你還應該使用if語句來檢查:if(File.Exists(filename)){web.DownloadFile。 ...} else {MesagesBox.Show(...); } –

+0

@BenjaminDangerJohnson謝謝。有效。但它沒有告訴我該文件已被下載。如果我想將此文件下載到此文件的名稱中,而不是a.zip,該怎麼辦? – aliboy38

回答

2

如果您使用DownloadFile而不是DownloadFileAsync,則不需要事件處理程序。

更新:從聊天結果發現OP希望文件系統上的文件名反映在URL末尾指定的文件名。這是解決方案:

private void button1_Click(object sender, EventArgs e) 
{ 
    Uri uri = new Uri("http://www.yourserver/path/to/yourfile.zip"); 
    string filename = Path.GetFileName(uri.LocalPath); 

    WebClient web = new WebClient(); 
    web.DownloadFile(new Uri(url), Path.Combine(@"f:\", filename)); 
} 
+0

它仍然有這個錯誤。它說:WebClient請求期間發生異常。 – aliboy38

+0

請發佈消息框中的全部輸出。 – tomfanning

+0

此外,我添加了更多代碼來幫助您解決此問題。 – tomfanning