7

我试图下载这样的文件:

WebClient _downloadClient = new WebClient();

_downloadClient.DownloadFileCompleted += DownloadFileCompleted;
_downloadClient.DownloadFileAsync(current.url, _filename);

// ...

下载后我需要使用下载文件启动另一个进程,我尝试使用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;
    }
}

但我不明白如何调用我的事件DownloadFileCompleted

对不起,如果它不是问题

4

2 回答 2

17

一种方法是创建一个闭包。

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 方法的文件名变量捕获并存储在闭包中。如果您不这样做,您将无法访问闭包中的文件名变量。

于 2012-12-17T19:36:09.550 回答
6

我正在玩DownloadFileCompleted从事件中获取文件路径/文件名。我也尝试过上述解决方案,但它不像我的预期那样我喜欢通过添加 Querystring 值的解决方案,在这里我想与你分享代码。

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
 }
于 2016-07-15T08:29:43.077 回答