【问题标题】:web client DownloadFileCompleted get file nameWeb 客户端 DownloadFileCompleted 获取文件名
【发布时间】:2012-12-17 15:27:27
【问题描述】:

我尝试下载这样的文件:

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问题

【问题讨论】:

标签: c# event-handling webclient


【解决方案1】:

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

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

【讨论】:

  • 这是我第一次看到 C# 中的闭包。我什至不知道这是可能的。非常感谢!
【解决方案2】:

我在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
 }

【讨论】:

  • 比公认的解决方案更简洁。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 2019-08-15
相关资源
最近更新 更多