现在我正在使用try-catch
来处理WebException
以确定我是否需要使用代理 - 这很难看。
不是使用try-catch
来控制程序执行,而是如果我需要使用代理,我想提前知道。
这是我的代码:
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;
}