向WebClient传递参数.DownloadFileCompleted事件

本文关键字:DownloadFileCompleted 事件 参数 WebClient | 更新日期: 2023-09-27 18:04:35

我正在使用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()传递参数

向WebClient传递参数.DownloadFileCompleted事件

您可以使用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;
     }
 }
相关文章:
  • 没有找到相关文章