我有以下有效的代码 - 上传文件,但既没有触发进度事件也没有触发完成事件。有什么想法吗?
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();
}
我试过上面的代码,预计事件会触发并提供有关完成和进度的反馈...
在您的代码中,您正在使用
UploadFileAsync
方法将文件上传到服务器。但是,由于是上传操作,DownloadProgressChanged
和 DownloadFileCompleted
事件不会被触发,因为它们是为跟踪下载操作而设计的。
WebClient.UploadProgressChanged
事件而不是DownloadProgressChanged
和WebClient.UploadFileCompleted
事件而不是DownloadFileCompleted
。此事件专门用于跟踪上传进度:
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
方法开始的。UploadFileAsync
每次异步上传取得进展时都会引发。当使用以下任何方法开始上传时会引发此事件:UploadProgressChanged
、UploadDataAsync
、UploadFileAsync
.UploadValuesAsync