下载完成后打开文件
本文关键字:文件 下载 | 更新日期: 2023-09-27 18:27:16
以下代码不起作用,不知何故,我无法将"Completed"方法的int值获取到我的btn_Start_Click方法:
private void btn_Start_Click(object sender, EventArgs e)
{
int completedDownload = 0;
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadFileAsync(new Uri("http://somesite.com/file.jpg"), @"c:'file.jpg");
if (Completed.completeDownload == 1)
{
//open the file code goes here.
}
//Rest of the code goes here.
//and here
//and here
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
completedDownload = 1;
}
根据WebClient.DownloadFileAsync
函数的备注:
文件是使用以下线程资源异步下载的自动从线程池中分配。接收通知当文件可用时,将事件处理程序添加到DownloadFileCompleted事件。
MSDN文档
当文件完成时激发函数似乎是一个更好的选择,需要使用事件处理程序。以下是使用DownloadFileCompleted
处理程序的示例:
// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);
// Specify that the DownloadFileCallback method gets called
// when the download completes.
client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
// Specify a progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileAsync (uri, "serverdata.txt");
}
MSDN文档
Completed处理程序异步执行。当你检查int时,没有保证hanlder已经设置了值。如果要在下载完成时执行某些操作,请在Completed方法中执行。