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 获取文件名


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01