2012-07-02 132 views
4

不,它不是那種基本問題。我正在做一個應用程序,並得到一個類似的文件,文件將被下載,然後它將被上傳到FTP服務器,然後本地副本將被刪除,然後一個條目將被放置在該文件名的字典中。所以,代碼是如何將參數傳遞給EventHandler

public void download_This_WebPage(string url, string cookies_String, string local_Saving_File_Name_With_Path) 
{ 
    WebClient wb = new WebClient(); 
    wb.Headers.Add(HttpRequestHeader.Cookie, cookies_String); 
    // Below I want to pass this local_File _Path to the event handler 
    wb.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wb,); 
    wb.DownloadFileAsync(new Uri(url), local_Saving_File_Name_With_Path + ".html"); 
} 

public void data_Download_Completed(Object sender, System.ComponentModel.AsyncCompletedEventArgs args) 
{ 
     //use the file name to upload the file to FTP 

} 

public FTP_Completed 
{ 
    // Delete the file 
} 

但是,我不知道如何將該文件名傳遞給download_Completed事件處理程序。可以有人指導我在這

編輯: 謝謝你從「達林」和「弗雷德裏克」的答案。是否有自定義的數據傳遞給(已定義)事件處理類似下面

void main_Fn() 
{ 
    string my_Data = "Data"; 
    some_object a = new some_object(); 
    some_Object.click_event += new eventHandler(click_Happened); 
    (Assume that the event passes two ints, I also want to pass the string "my_Data" 
     to "click_Happened") 
    some_object.start(); 
} 

void click_Happened(int a, int b) 
{ 
    // I want to get the string "my_Data" here. 
} 

總之如何欺騙簽名任何通用的方式?

回答

6

可以傳遞userToken參數中的文件名稱爲DownloadFileAsync()。當操作完成後,它會在AsyncCompletedEventArgs參數傳遞的UserState財產可供data_Download_Completed()

string filename = local_Saving_File_Name_With_Path + ".html"; 
wb.DownloadFileAsync(new Uri(url), filename, filename); 

然後:

public void data_Download_Completed(Object sender, 
    System.ComponentModel.AsyncCompletedEventArgs args) 
{ 
    string filename = (string) args.UserState; 
    // Now do something with 'filename'... 
} 
+0

感謝您的解決方案。但是,無論如何要將用戶定義的數據注入事件處理程序? – prabhakaran

+1

@prabhakaran,那麼你可以在'userToken'中傳遞任何類型,包括任何'class'或'struct'的實例,它將在'UserState'中可用。 –

+0

原諒我的語法錯誤。我的意思是如何對任何事件處理程序執行此操作? – prabhakaran

1

你可以使用DownloadFileAsync方法,可以讓你的UserState傳遞到完成處理的3擋的說法:

// subscribe to the completed event 
wb.DownloadFileCompleted += data_Download_Completed; 
string file = local_Saving_File_Name_With_Path + ".html"; 
wb.DownloadFileAsync(new Uri("url"), file, file); 

和處理程序中:

public void data_Download_Completed(Object sender, AsyncCompletedEventArgs args) 
{ 
    // extract the filename from the UserState of the args 
    string file = args.UserState as string; 
    ... 

} 
+0

我不知道是誰第一個提出了答案。感謝您的解決方案。同樣的問題給你。有沒有辦法將用戶定義的數據注入事件處理程序。 – prabhakaran

+0

是的,使用我的答案中所示的UserState屬性。您可以傳遞任意複雜的對象而不是簡單的字符串。 –

+0

原諒我的語法錯誤。我的意思是如何對任何事件處理程序執行此操作? – prabhakaran