如何使用Webclient捕获任何错误?

问题描述

| 我正在尝试使用WebClient捕获连接问题。例如,无法访问,超时等。下面的代码不起作用,好像没有错误
WebClient wc = new WebClient();
try
{
    wc.UploadFileAsync(new Uri(@\"ftp://tabletijam/FileServer/upload.bin\"),Directory.GetCurrentDirectory() + @\"\\crypto.bin\");
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString());
}
    

解决方法

您使用的代码只是发送文件...您需要实现异步部分。
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address,fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
webClient.UploadFileCompleted += WebClientUploadCompleted;

...

void WebClientUploadProgressChanged(object sender,UploadProgressChangedEventArgs e)
{
     Console.WriteLine(\"Download {0}% complete. \",e.ProgressPercentage);
}
void WebClientUploadCompleted(object sender,UploadFileCompletedEventArgs e)
{
    // The upload is finished,clean up
}
    ,
try
{
    // trying to make any operation on a file
}
catch (IOException error)
{
    if(error is FileNotFoundException)
    {
        // Handle this error
    }
}
使用此代码,但与您的方案有关