如何使用WebClient()下载文件时避免应用程序崩溃;

Bad*_*ari 2 c# crash webclient

我正在使用C#WebClient(); 从服务器下载文件.问题是当我没有互联网或服务器没有响应时,我的应用程序崩溃尝试下载此文件.避免崩溃,中止并通知与服务器的连接失败的最佳做法是什么?

Ree*_*sey 5

只需处理WebClient.DownloadFile返回的异常:

try
{
    WebClient.DownloadFile(uri, myPath);
}
catch(WebException webEx)
{
     // There was an exception due to network or path problems...
     // Notify the user? 
}
Run Code Online (Sandbox Code Playgroud)