开发者

C# webClient.DownloadFile exception issues

开发者 https://www.devze.com 2023-03-29 12:32 出处:网络
Currently I have a very simple code that downloads a file from a server, however i keep running into the following exceptions:

Currently I have a very simple code that downloads a file from a server, however i keep running into the following exceptions:

The remote server returned an error: (500)

Unable to connect to the remote server

There is nothing wrong with the webserver it has to do with my service and i guess it times out, how can i handle these more robustly? I have my code shown below, it's really simple.

            try
        {
            string[] splitCrawlerid = StaticStringClass.crawlerID.Split('t');
            WebClient webClient = new WebClient();
            if (Directory.Exists("C:\\ImageDepot\\" + splitCrawlerid[2]))
            {

            }
            else
            {
                Directory.CreateDirectory("C:\\ImageDepot\\" + splitCrawlerid[2]);

            }
            webClient.DownloadFile(privateHTML, @"C:\ImageDepot\" + splitCrawlerid[2] + "\\"开发者_JAVA百科 + "AT" + carID + ".jpeg");
        }
        catch (Exception ex)
        {
//not sure how to really handle these two exceptions reliably
}

The ideal situation for me would be to attempt to download the file again.


Try setting a user-agent header. The WebClient doesn't send that be default and MSDN warns that some web servers will return a 500 error if user-agent isn't set.

A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.

See the example on the MSDN page for how to add the header.


You could wrap the whole thing in a for loop that goes 0..3, and the line after webClient.DownloadFile(...) could be a break;. That way if there's an exception, the break gets skipped and the app tries again. But that seems to be more of a band-aid to me; I'd spend more time figuring out exactly why things are going wrong.

If you want to remove all the "try while blah else until rethrow whatever" code from the business logic of your app, you could define an extension method like

public static T TryNTimes<T>(this Func<T> func, int n) {
    while (true) {
        try {
            return func();
        } catch {
            if (++i == n) throw;
        }
    }
}

and use it like

Func<File> downloader = () => client.DownloadFile(...);
var file = downloader.TryNTimes(5);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号