7

私はこのようなファイルをダウンロードしようとしました:

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

それがうんざりする質問ならごめんなさい

4

2 に答える 2

17

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メソッドに渡されたfilename変数がキャプチャされ、クロージャーに格納されるようにするためです。これを行わなかった場合、クロージャー内のファイル名変数にアクセスできません。

于 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 に答える