I have the following code that works - uploads the file, but neither progress nor completion events are fired. Any ideas why?
try
{
string srcFilePath = @"C:\Projects\MySetup.zip";
string url = "ftp://xxx.xxx.xxx.xxx/downloads/MySetup.zip";
Uri uri = new Uri(url);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("userName", "pass");
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadProgressChanged += Client_DownloadProgressChanged;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.UploadFileAsync(uri, srcFilePath);
}
catch(System.Net.WebException e)
{
Console.WriteLine(e.Message + ": " + e.Status);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private static void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine(String.Format("Percent complete: {0}", e.ProgressPercentage));
}
private static void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
doneEvent.Set();
}
I tried the above code and expected that the event will fire and will provide feedback about completion and progress...
In your code, you are using UploadFileAsync
method to upload a file to the server. However, since it is an upload operation, the DownloadProgressChanged
and DownloadFileCompleted
events will not be fired because they are designed for tracking download operations.
You should use WebClient.UploadProgressChanged
event instead of DownloadProgressChanged
and WebClient.UploadFileCompleted
event instead of DownloadFileCompleted
. This events are specifically designed for tracking upload progress:
client.UploadFileCompleted += Client_UploadFileCompleted;
client.UploadProgressChanged += Client_UploadProgressChanged;
...
private static void Client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine(String.Format("Percent complete: {0}", e.ProgressPercentage));
}
private static void Client_UploadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
doneEvent.Set();
}
UploadFileCompleted
is raised each time an asynchronous file upload operation completes. Asynchronous file uploads are started by calling theUploadFileAsync
methods.
UploadProgressChanged
is raised each time an asynchronous upload makes progress. This event is raised when uploads are started using any of the following methods:UploadDataAsync
,UploadFileAsync
,UploadValuesAsync
.