2012-12-17 10 views
5

ファイル名取得DownloadFileCompleted:Webクライアントは、私はこのようなファイルをダウンロードしようとした

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; 
    } 
} 

しかし、私はそれはnood質問

かどう代わり DownloadFileCompleted

申し訳ありませんが、私のイベントを呼び出す方法を理解することはできません

+0

http://msdn.microsoft.com/en-us/library/17sde2xt(v=VS.100).aspx – Leri

+0

たぶんグローバル変数 – VladL

+0

私はどのようにイベントを使用するか知っています=)私は私のイベントを代わりに使用する方法を知っていません.ArtArgsでDownloadFileCompleted – user1644087

答えて

12

1つの方法はクロージャを作成することです。

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

これは、DownloadFileCompletedがイベントハンドラを返す必要があることを意味します。 DownloadFileCompleteメソッドに渡されたファイル名の変数が捕捉され、閉鎖に格納されているように

 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); 
     } 

Iは_filenameという変数を作成する理由があります。これをしなかった場合、クロージャ内のファイル名変数にアクセスすることはできません。

+0

すごく感謝!それは仕事です! – user1644087

+0

私は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 
}