【问题标题】:How to capture any error with Webclient?如何使用 Webclient 捕获任何错误?
【发布时间】:2011-03-17 08:36:50
【问题描述】:

我尝试在使用 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());
}

【问题讨论】:

  • 嗯......提供的代码sn-p应该有什么问题吗?
  • 代码没有错。我做了什么,但我仍然不知道上传是否开始。我想要实现的是,我如何知道客户端主机是否无法访问,或者传输是否有问题?

标签: c# .net debugging webclient


【解决方案1】:

您正在使用的代码,只是发送文件...您需要实现 Async 部分。

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
}

【讨论】:

    【解决方案2】:
    try
    {
        // trying to make any operation on a file
    }
    catch (IOException error)
    {
        if(error is FileNotFoundException)
        {
            // Handle this error
        }
    }
    

    在您的场景中使用此代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2015-04-22
      • 2021-09-01
      • 2017-09-17
      相关资源
      最近更新 更多