Download Async + Copy = Copying image 0 bytes

Asked

Viewed 44 times

1

I am simultaneously downloading several photos, and also need to make the copy to a certain folder.

What happens is that it makes 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);
        }

Summary example of photoProducts

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

How to understand that certain task finished (downloaded ) and so I can make the copy?

I thought I’d make out of Whenall something like

 await Task.WhenAll(urlTasks);

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

                }
            }

But how would I know which one of the urls he already processed? I’m having a hard time.

1 answer

2


Any code you place after await Task.WhenAll(urlTasks);will be executed when all task finished.

You can then make a copy of all downloaded files:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.