2012-12-17 49 views
5

我試圖下載的文件是這樣的:Web客戶端DownloadFileCompleted獲取文件名

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問題

+0

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

+0

也許全球變量 – VladL

+0

我知道如何使用事件=)我不知道如何使用我的事件而不是DownloadFileCompleted與我的eventArgs – user1644087

回答

12

一種方法是創建一個閉包。

 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方法的文件名變量被捕獲並存儲在所述封閉。如果你沒有這樣做,你將無法訪問閉包中的文件名變量。

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