I tried to download file like this:
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted;
_downloadClient.DownloadFileAsync(current.url, _filename);
// ...
And after downloading I need to start another process with download file, I tried to use DownloadFileCompleted
event.
void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
throw e.Error;
}
if (!_downloadFileVersion.Any())
{
complited = true;
}
DownloadFile();
}
But, i cannot know name of downloaded file from AsyncCompletedEventArgs
, I made my own
public class DownloadCompliteEventArgs: EventArgs
{
private string _fileName;
public string fileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
public DownloadCompliteEventArgs(string name)
{
fileName = name;
}
}
But I cannot understand how call my event instead DownloadFileCompleted
Sorry if it's nood question
One way is to create a closure.
WebClient _downloadClient = new WebClient();
_downloadClient.DownloadFileCompleted += DownloadFileCompleted(_filename);
_downloadClient.DownloadFileAsync(current.url, _filename);
This means your DownloadFileCompleted needs to return the event handler.
public AsyncCompletedEventHandler DownloadFileCompleted(string filename)
{
Action<object, AsyncCompletedEventArgs> 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.
I was playing around DownloadFileCompleted
to get the file path/file name From the event. I've tried the above solution also but It was not like my expectation then i fond the solution by adding Querystring value, Here i would like to share the code with you.
string fileIdentifier="value to remember";
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCompleted);
webClient.QueryString.Add("file", fileIdentifier); // here you can add values
webClient.DownloadFileAsync(new Uri((string)dyndwnldfile.path), localFilePath);
And the event can be defined as like this:
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
string fileIdentifier= ((System.Net.WebClient)(sender)).QueryString["file"];
// process with fileIdentifier
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With