将参数传递给WebClient.DownloadFileCompleted事件 [英] Pass parameters to WebClient.DownloadFileCompleted event

查看:516
本文介绍了将参数传递给WebClient.DownloadFileCompleted事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的代码:

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()?

推荐答案

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

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

然后在您的DoSomethingOnFinish函数中访问它

Then to access it in your DoSomethingOnFinish function,

使用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类.您可能还没有听说过,但这应该是这样:

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

这篇关于将参数传递给WebClient.DownloadFileCompleted事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆