passing filename to DownloadFileCompleted in async file download using webClient C#

StackOverflow https://stackoverflow.com/questions/22865612

  •  27-06-2023
  •  | 
  •  

質問

My program is using queue to download list of files one by one in a async method using webClient . It looks like this:

    public void DownloadFile()
    {
        if (_downloadUrls.Any())
        {
            var urlAddress = _downloadUrls.Dequeue();
            //Irrelevant code that gets correct URL, and location from queue _downloadUrls

            try
            {
                // Start downloading the file
                webClient1.DownloadFileAsync(URL, location);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        else
        {
            MessageBox.Show("complete!");
        }
    }

Here is my DownloadFileCompleted code:

private void webClient1_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            // MessageBox.Show("Download has been canceled.");
        }
        else
        {
            DownloadFile();
        }
    }

Quesion is how can i pass info about filename to DownloadFileCompleted? I want to change last access date of downloaded files so they woud be the same like on the server and i can only do this in webClient1_DownloadFileCompleted but i don't know which file triggered event DownloadFileCompleted. How can i pass this info to DownloadFileCompleted (preferably as string in parameter).

役に立ちましたか?

解決

Use the overload method WebClient.DownloadFileAsync(Uri address, string fileName, object userToken), you can pass the file name as the userToken and then access it in the DownloadFileCompleted handler.

userToken: A user-defined object that is passed to the method invoked when the asynchronous operation completes.

http://msdn.microsoft.com/en-us/library/ms144197(v=vs.110).aspx

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top