5

不,这不是那种基本的问题。我正在做一个应用程序并得到一个类似的场景,文件将被下载然后上传到 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 的事件处理程序。有人可以指导我吗

编辑: 感谢“达林”和“弗雷德里克”的回答。是否有任何通用方法可以将自定义数据传递给(已定义)事件处理程序,如下所示

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

总之如何欺骗签名?

4

2 回答 2

7

userToken您可以将参数中的文件名传递给DownloadFileAsync()。操作完成后,它将在传递给的AsyncCompletedEventArgsUserState参数的属性中可用: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'...
}
于 2012-07-02T09:31:20.843 回答
1

您可以使用该方法的第三个参数,DownloadFileAsync它允许您将一个传递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;
    ...

}
于 2012-07-02T09:31:14.243 回答