2012-12-17 4 views
5

파일 이름 얻을 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; 
    } 
} 

그러나 나는 그것이 NOOD 질문

의 경우 대신 DownloadFileCompleted

미안 내 이벤트를 호출하는 방법을 이해할 수 없다

+0

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

+0

아마도 전역 변수 – VladL

+0

어떻게 사용 이벤트 =) 알고 내 이벤트 대신 내 이벤트를 사용하십시오 .Art EventArgs와 함께 DownloadFileCompleted – user1644087

답변

12

한 가지 방법은 클로저를 만드는 것입니다.

 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 
} 
관련 문제