我试图下载的文件是这样的:
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted;
_downloadClient.DownloadFileAsync(current.url, _filename);
// ...
和下载后,我开始需要下载文件的另一个过程中,我试图用DownloadFileCompleted
事件。
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;
}
}
但我不明白,而不是怎么称呼我的事件DownloadFileCompleted
如果它是对不起nood问题
一种方法是创建一个封闭。
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted(_filename);
_downloadClient.DownloadFileAsync(current.url, _filename);
这意味着你的DownloadFileCompleted需要返回事件处理程序。
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方法的文件名变量被捕获并存储在所述封闭。 如果你不这样做,你不会有机会获得封内的文件名可变。
我玩弄DownloadFileCompleted
得到的文件路径/文件名从事件。 我已经尝试了上述解决方法还,但它不是像我期望的话,我喜欢通过添加查询字符串值的解决方案,在这里,我想与大家分享的代码。
string fileIdentifier="value to remember";
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCompleted);
webClient.QueryString.Add("file", fileIdentifier); // here you can add values
webClient.DownloadFileAsync(new Uri((string)dyndwnldfile.path), localFilePath);
而事件可以定义为这样的:
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
string fileIdentifier= ((System.Net.WebClient)(sender)).QueryString["file"];
// process with fileIdentifier
}