Web 客户端 DownloadFileCompleted 获取文件名

web client DownloadFileCompleted get file name(Web 客户端 DownloadFileCompleted 获取文件名)

本文介绍了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 获取文件名

基础教程推荐