How to pass an argument to EventHandler

No, this is not such a basic question. I make an application and get scenerio, like, the file will be uploaded, then it will be uploaded to the FTP server, then the local copy will be deleted, then one entry will be placed in the dictionary for this file name. So the code below

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 } 

But I do not know how to pass this file name to the download_Completed event handler. Can anyone help me on this

EDIT: Thanks for the answers from Darina and Frederick. Is there any general way to pass user data to an event handler (already defined) as shown below.

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

In short, how to trick a signature?

+4
source share
2 answers

You can pass the file name in the userToken argument to DownloadFileAsync () . When the operation completes, it will be available in the UserState property of the UserState argument passed to data_Download_Completed() :

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

Then:

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

You can use the 3rd argument of the DownloadFileAsync method, which allows you to pass the UserState to the completed handler:

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

and inside the handler:

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

All Articles