如何捕获 Webclient 的任何错误?

发布于 2024-10-23 01:06:42 字数 326 浏览 2 评论 0原文

我试图捕获使用 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());
}

Im trying to capture connection problem when using WebClient. Example, unreachable, timeout etc. Code belows doesnt work, as if there is nothing wrong.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

输什么也不输骨气 2024-10-30 01:06:42

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

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
}

The code you are using, just sends the file ... you need to implement the Async part.

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
}
一袭水袖舞倾城 2024-10-30 01:06:42
try
{
    // trying to make any operation on a file
}
catch (IOException error)
{
    if(error is FileNotFoundException)
    {
        // Handle this error
    }
}

使用此代码但适合您的场景

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

use this code but with your scenario

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文