2013-06-28 92 views
1

使用下面的代碼,但它根本沒有下載任何文件到名爲myImages的指定子文件夾到應用程序......我該如何解決這個問題?這裏的鏈接純粹就是一個例子,鏈接通常是一個變量,並且沒有任何問題。這一切都是在BackgroundWorker中完成的,否則將100%正常工作。C#下載文件不起作用

//File to download 
string _fileToDownload = "http://www.codeproject.com/images/download24.png" 
//Path to download files 
string _filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "MyImages\\download24.png'"; 
//Download the image 
using (var webClient = new WebClient()) 
{ 
    webClient.DownloadFileAsync(new Uri(_fileToDownload), @_filePath); 
} 

謝謝。

回答

1

在你的情況下不需要使用異步文件下載。這應該工作:

webClient.DownloadFile(_fileToDownload, _filePath); 
+0

它不想工作。我在一個已經運行的後臺工作者中使用代碼,並且當我將其更改爲非異步方法進行下載時,它說我的後臺工作已完成(這是錯誤的,因爲它應該工作一段時間)。 ..這隻發生在DownloadFile方法而不是ASync方法,但ASync方法不會下載任何東西 – touyets

0

所以WebClient.DownloadFileAsync方法只創建一個Task下載你需要真正開始下載文件(通過調用Task.StartTask.RunSyncronously)任務的文件,也可以致電syncronous API

//File to download 
string _fileToDownload = "http://www.codeproject.com/images/download24.png" 
//Path to download files 
string _filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "MyImages\\download24.png'"; 
//Download the image 
using (var webClient = new WebClient()) 
{ 
    //Set the banner variable 
    webClient.DownloadFile(new Uri(_fileToDownload), @_filePath); 
} 
+0

我怎麼能從理論上啓動這項任務? – touyets

+0

'webclient.DownloadFileAsync(new Uri(_fileToDownload),@_filePath).Start()'should work,or if this is in'async' method you can always'await webclient.DownloadFileAsync(new Uri(_fileToDownload) _filePath);' – Mgetz

0

使用同步下載方法。

webClient.DownloadFile(new Uri(_fileToDownload), @_filePath); 
+0

它不想工作。我在一個已經運行的後臺工作者中使用代碼,並且當我將其更改爲非異步方法進行下載時,它說我的後臺工作已完成(這是錯誤的,因爲它應該工作一段時間)。 ..這隻發生在DownloadFile方法而不是ASync方法,但ASync方法不會下載任何東西 – touyets

0

試試這個代碼 -

string remoteUri = "http://www.codeproject.com/images/"; 
string fileName = "download24.png"; 
StringWebResource = null; 
// Create a new WebClient instance. 
WebClient myWebClient = new WebClient(); 
// Concatenate the domain with the Web resource filename. 
myStringWebResource = remoteUri + fileName; 
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource); 
// Download the Web resource and save it into the current filesystem folder. 
myWebClient.DownloadFile(myStringWebResource,fileName);  
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource); 
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath); 
+0

use System.Net.WebClient.Download – Dinesh

3

確定。 emmmmmmmmm找到了我的答案:的確,我可以使用文件下載方法,但對我來說,輸入正確的保存路徑是有用的......這是正確的路徑,我忘了在我的文件夾名稱前放上一個\ ...

string _filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\MyImages\\download24.png'"; 
+0

如果這是你的答案,那你爲什麼接受另一個? – Imad