将参数传递给WebClient.DownloadFileCompleted事件

时间:2016-08-29 11:17:43

标签: c# asynchronous unity3d unity5

我正在使用WebClient.DownloadFileAsync()方法,并想知道如何将参数传递给WebClient.DownloadFileCompleted事件(或任何其他事件),并在调用的方法中使用它。

我的代码:

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?
    }

}

如何将参数传递给DoSomethingOnFinish()

1 个答案:

答案 0 :(得分:6)

您可以使用webClient.QueryString.Add("FileName", YourFileNameID);添加额外信息。

然后在DoSomethingOnFinish函数

中访问它

使用string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["FileName"];接收文件名。

这就是代码的样子:

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"];
}

即使这应该有效,你应该使用Unity的UnityWebRequest类。你可能没有听说过它,但它应该是这样的:

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