Pass parameters to WebClient.DownloadFileCompleted event

梦想的初衷 提交于 2019-12-10 18:56:48

问题


I am using the WebClient.DownloadFileAsync() method, and wanted to know how can i pass a parameter to the WebClient.DownloadFileCompleted event (or any other event for that matter), and use it in the invoked method.

My code:

public class MyClass
{
    string downloadPath = "some_path";
    void DownloadFile()
    {
        int fileNameID = 10;
        WebClient webClient = new WebClient();
        webClient.DownloadFileCompleted += DoSomethingOnFinish;
        Uri uri = new Uri(downloadPath + "\" + fileNameID );
        webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\" + fileNameID); 
    }

    void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
    {
        //How can i use fileNameID's value here?
    }

}

How can I pass a parameter to DoSomethingOnFinish()?


回答1:


You can use webClient.QueryString.Add("FileName", YourFileNameID); to add extra information.

Then to access it in your DoSomethingOnFinish function,

use string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["FileName"]; to receive the file name.

This is what the code should look like:

string downloadPath = "some_path";
void DownloadFile()
{
    int fileNameID = 10;
    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish);
    webClient.QueryString.Add("fileName", fileNameID.ToString());
    Uri uri = new Uri(downloadPath + "\\" + fileNameID);
    webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\\" + fileNameID); 
}

void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
    //How can i use fileNameID's value here?
    string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"];
}

Even if this should work, you should be using Unity's UnityWebRequest class. You probably haven't heard about it but this is what it should look like:

void DownloadFile(string url)
 {
     StartCoroutine(downloadFileCOR(url));
 }

 IEnumerator downloadFileCOR(string url)
 {
     UnityWebRequest www = UnityWebRequest.Get(url);

     yield return www.Send();
     if (www.isError)
     {
         Debug.Log(www.error);
     }
     else
     {
         Debug.Log("File Downloaded: " + www.downloadHandler.text);

         // Or retrieve results as binary data
         byte[] results = www.downloadHandler.data;
     }
 }


来源:https://stackoverflow.com/questions/39204967/pass-parameters-to-webclient-downloadfilecompleted-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!