Download Async + Copy = Copying image 0 bytes

1

I'm downloading simultaneously multiple photos, and also need to copy to a certain folder.

What happens is that it does the copy before finishing the download.

public static async Task DownloadData(IEnumerable<FotosProdutos> urls, int id)
        {
            var urlTasks = urls.Select((url, index) =>
            {
                //corrigo possíveis erros na url
                var urlTratada = url.Url.Replace(" ", "").Replace("\n", "");

                using (var wc = new WebClient())
                {
//Caminhos.FolderImg é uma const do tipo @"C:\files\"
                    var path = Caminhos.FolderImg +  url.FileName;


                    var downloadTask = wc.DownloadFileTaskAsync(new Uri(urlTratada), path);
//aqui é minha tentativa de só fazer o copy depois q estiver ok, porém com esse if nunca é executado.
                    if(downloadTask.IsCompleted)
                    {
                        File.Copy(Caminhos.FolderImg + url.FileName, Caminhos.FolderImg + @"\tb\" + url.FileName);
                    }



                    Console.WriteLine(String.Format("{0} - DownloadFtos {1} - {2}", DateTime.Now, index.ToString(), id.ToString()));

                    return downloadTask;
                }
            });

            await Task.WhenAll(urlTasks);
        }

Short photo exampleProducts

public class FotosProdutos()
{
 public string Url {get; set;}
 public string FileName {get; set;}
}

How to understand that particular task completed (downloaded) and so can I copy?

I thought about doing something out of WhenAll

 await Task.WhenAll(urlTasks);

            foreach (var item in urlTasks)
            {
                if (item.IsCompleted)
                {

                }
            }

But how would you know which of the urls he has already sued? I'm having difficulties.

    
asked by anonymous 14.10.2016 / 16:28

1 answer

2

Any code that follows the await Task.WhenAll(urlTasks); se will be executed when all the task has finished.

You can then copy all downloaded files:

    .....
    .....
    await Task.WhenAll(urlTasks);

    foreach (var url in urls)
    {
        File.Copy(Caminhos.FolderImg + url.FileName, Caminhos.FolderImg + @"\tb\" + url.FileName);
    }
}
    
14.10.2016 / 16:57