在 C# 中使用 WebClient 上传 FTP 文件的进展

问题描述 投票:0回答:1

我有以下有效的代码 - 上传文件,但既没有触发进度事件也没有触发完成事件。有什么想法吗?

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();
}

我试过上面的代码,预计事件会触发并提供有关完成和进度的反馈...

c# events ftp webclient
1个回答
0
投票

在您的代码中,您正在使用

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
.

© www.soinside.com 2019 - 2024. All rights reserved.