gpt4 book ai didi

c# - 将参数传递给 WebClient.DownloadFileCompleted 事件

转载 作者:行者123 更新时间:2023-11-30 14:07:38 25 4
gpt4 key购买 nike

我正在使用 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.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;
}
}

关于c# - 将参数传递给 WebClient.DownloadFileCompleted 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com