Web客户端DownloadFileCompleted获取文件名 [英] web client DownloadFileCompleted get file name
问题描述
我试图下载的文件是这样的:
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
,我做我自己
public class DownloadCompliteEventArgs: EventArgs
{
private string _fileName;
public string fileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
public DownloadCompliteEventArgs(string name)
{
fileName = name;
}
}
但我无法理解,而不是<$怎么称呼我的事件C $ C> 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需要返回事件处理程序。
Which 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获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!