0

Right now I am using a try-catch to handle a WebException in order to determine whether or not I need to use a proxy - it's ugly.

Rather than use try-catch to control program execution, I'd like to know up front if I need to use a proxy.

Here is my code:

private bool m_useDefaultWebProxy;

public void DownloadFile(String url, String fileName) {
    try {
        using (WebClient webClient = new WebClient()) {
            if (m_useDefaultProxy) {
                this.SetDefaultProxy(webClient)
            }
            webClient.DownloadFile(url, fileName);
        }
    }
    catch (WebException ex) {
        this.HandleWebProxyError(ex);
    }
}

private void HandleWebProxyError(WebException ex) {
    HttpStatusCode = ((HttpWebResponse)ex.Response).StatusCode;
    if (statusCode == HttpStatusCode.ProxyAuthenticationRequired) {
        this.m_useDefaultWebProxy.Checked = true;        
    }
}

private void SetDefaultWebProxy(WebClient webClient) {
    IWebProxy proxy = WebRequest.GetSystemWebProxy();
    proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
    webClient.Proxy = proxy;
}
Ian R. O'Brien
  • 6,122
  • 9
  • 40
  • 71
  • 2
    Just out of curiosity, what happens when you provide a proxy when you don't *need* one? I'm asking because I usually always supply it and it works in both cases. But I understand that there could be scenarios that I have not come across. – Andrew Savinykh Feb 08 '13 at 19:02
  • Honestly. I don't think this code is all that ugly. I think you handle the situation appropriately. The first request comes in, throws an exception, you auto check the box and then from then on out use a proxy. I like it. – Al W Feb 08 '13 at 19:04
  • @zespri I wondered this myself but I'm not behind a proxy to test this unfortunately. It would probably be okay I think since I'm just using `GetSystemWebProxy` but I wanted to be sure. – Ian R. O'Brien Feb 08 '13 at 19:12
  • Don't you need to retry after the exception? – Miserable Variable Feb 08 '13 at 19:15
  • @MiserableVariable yes, I would need to, which is why I'd rather know if I need to set the proxy before I make the web call. – Ian R. O'Brien Feb 08 '13 at 19:40

0 Answers0