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