Search code examples
c#delegateseventhandler

Create own EventHandler from DownloadProgressChangedEventHandler - is this possible?


Good evening, I try to create an own EventHandler on the base of the DownloadProgressChangedEventHandler. The reason is, I want to give the Callback function an extra parameter (fileName). This is my EventHandler:

 public class MyDownloadProgressChangedEventHandler : DownloadProgressChangedEventHandler
    {

        public object Sender { get; set; }

        public DownloadProgressChangedEventArgs E { get; set; }

        public string FileName { get; set; }

        public MyDownloadProgressChangedEventHandler(object sender, DownloadProgressChangedEventArgs e, string fileName)
        {
            this.Sender = sender;
            this.E = e;
            this.FileName = fileName;
        }

    }

And this is my attempt:

WebClient client = new WebClient();

client.DownloadProgressChanged += new MyDownloadProgressChangedEventhandler(DownloadProgressChanged);
client.DownloadFileAsync(new Uri(String.Format("{0}/key={1}", srv, file)), localName);

Console.WriteLine(String.Format("Download of file {0} started.", localName));
Console.ReadLine();

But VS says that a conversation from MyDownloadProgressChangedEventHandler to the DownloadProgressChangedEventHandler is not possible. Is this even possible like how I think?

Thanks in advance.


Solution

  • How should the WebClient know what to put inside your defined variable? (it can't)

    Instead, wrap the handler you got inside another one:

    string fileName = new Uri(String.Format("{0}/key={1}", srv, file));
    client.DownloadProgressChanged += 
        (sender, e) =>
            DownloadProgressChanged(sender, e, fileName);
    client.DownloadFileAsync(fileName);
    

    Lambda expressions are always fun to use in these situations!