web client DownloadFileCompleted get file name(Web 客户端 DownloadFileCompleted 获取文件名)
问题描述
我尝试下载这样的文件:
I tried to download file like this:
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted;
_downloadClient.DownloadFileAsync(current.url, _filename);
// ...
下载后我需要使用下载文件启动另一个进程,我尝试使用 DownloadFileCompleted
事件.
And after downloading I need to start another process with download file, I tried to use DownloadFileCompleted
event.
void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
throw e.Error;
}
if (!_downloadFileVersion.Any())
{
complited = true;
}
DownloadFile();
}
但是,我不知道从 AsyncCompletedEventArgs
下载的文件的名称,我自己做了
But, i cannot know name of downloaded file from AsyncCompletedEventArgs
, I made my own
public class DownloadCompliteEventArgs: EventArgs
{
private string _fileName;
public string fileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
public DownloadCompliteEventArgs(string name)
{
fileName = name;
}
}
但我不明白如何改为调用我的事件 DownloadFileCompleted
But I cannot understand how call my event instead DownloadFileCompleted
对不起,如果是nood问题
Sorry if it's nood question
推荐答案
一种方法是创建一个闭包.
One way is to create a closure.
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted(_filename);
_downloadClient.DownloadFileAsync(current.url, _filename);
这意味着您的 DownloadFileCompleted 需要返回事件处理程序.
This means your DownloadFileCompleted needs to return the event handler.
public AsyncCompletedEventHandler DownloadFileCompleted(string filename)
{
Action<object, AsyncCompletedEventArgs> action = (sender, e) =>
{
var _filename = filename;
if (e.Error != null)
{
throw e.Error;
}
if (!_downloadFileVersion.Any())
{
complited = true;
}
DownloadFile();
};
return new AsyncCompletedEventHandler(action);
}
我创建名为 _filename 的变量的原因是为了将传递给 DownloadFileComplete 方法的文件名变量捕获并存储在闭包中.如果你不这样做,你将无法访问闭包中的文件名变量.
The reason I create the variable called _filename is so that the filename variable passed into the DownloadFileComplete method is captured and stored in the closure. If you didn't do this you wouldn't have access to the filename variable within the closure.
这篇关于Web 客户端 DownloadFileCompleted 获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Web 客户端 DownloadFileCompleted 获取文件名
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01