web client DownloadFileCompleted get file name

前端 未结 2 455
借酒劲吻你
借酒劲吻你 2021-01-12 21:08

I tried to download file like this:

WebClient _downloadClient = new WebClient();

_downloadClient.DownloadFileCompleted += DownloadFileCompleted;
_downloadCl         


        
2条回答
  •  死守一世寂寞
    2021-01-12 21:27

    One way is to create a closure.

            WebClient _downloadClient = new WebClient();        
            _downloadClient.DownloadFileCompleted += DownloadFileCompleted(_filename);
            _downloadClient.DownloadFileAsync(current.url, _filename);
    

    Which means your DownloadFileCompleted needs to return the event handler.

            public AsyncCompletedEventHandler DownloadFileCompleted(string filename)
            { 
                Action action = (sender,e) =>
                {
                    var _filename = filename;
    
                    if (e.Error != null)
                    {
                        throw e.Error;
                    }
                    if (!_downloadFileVersion.Any())
                    {
                        complited = true;
                    }
                    DownloadFile();
                };
                return new AsyncCompletedEventHandler(action);
            }
    

    The reason I create the variable called _filename is so that the filename variable passed into the DownloadFileComplete method is captured and stored in the closure. If you didn't do this you wouldn't have access to the filename variable within the closure.

提交回复
热议问题