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

时间:2011-03-17 08:36:50

标签: c# .net debugging 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());
}

2 个答案:

答案 0 :(得分:0)

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

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
}

答案 1 :(得分:0)

try
{
    // trying to make any operation on a file
}
catch (IOException error)
{
    if(error is FileNotFoundException)
    {
        // Handle this error
    }
}

使用此代码,但使用您的方案