如何将参数传递给EventHandler

时间:2012-07-02 09:26:17

标签: c#

不,不是那种基本问题。我正在做一个应用程序并得到一个类似的场景,文件将被下载然后它将被上传到FTP服务器,然后本地副本将被删除,然后一个条目将被放置在该文件名的字典中。所以,代码在

之下
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的事件处理程序。任何人都可以指导我

修改    感谢来自" Darin"和"弗雷德里克"。是否有任何通用的方法将自定义数据传递给(已定义的)事件处理程序,如下所示

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

总之如何欺骗签名?

2 个答案:

答案 0 :(得分:6)

您可以将userToken参数中的文件名传递给DownloadFileAsync()。操作完成后,它将在传递给UserState的{​​{3}}参数的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'...
}

答案 1 :(得分:1)

您可以使用DownloadFileAsync方法的第3个参数,该方法允许您将UserState传递给已完成的处理程序:

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

}