C# Загрузка файла не работает

Используя приведенный ниже код, но он не загружает никаких файлов в указанную подпапку с именем myImages для приложения... Как это исправить? Ссылка здесь приведена исключительно в качестве примера, обычно ссылка будет переменной, и в ней нет проблем с заполнением. Все это делается в BackgroundWorker, который в противном случае работает на 100%.

//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);
}

Благодарю.

5 ответов

Решение

В вашем случае нет необходимости использовать асинхронную загрузку файлов. Это должно работать:

 webClient.DownloadFile(_fileToDownload, _filePath);

Хорошо. emmmmmmmmm нашел мой ответ: на самом деле я могу использовать метод загрузки файла, но мне было бы полезно ввести правильный путь сохранения... это был правильный путь, я забыл поставить \ перед именем папки....

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

Итак WebClient.DownloadFileAsync метод только создает Task чтобы скачать файл, вам нужно запустить задачу загрузки файла (либо Task.Start или же Task.RunSyncronously) или вы можете вызвать синхронный 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);
}

Попробуйте этот код

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);

Используйте метод синхронной загрузки.

  webClient.DownloadFile(new Uri(_fileToDownload ), @_filePath);
Другие вопросы по тегам