现在我正在使用 atry-catch
来处理 aWebException
以确定我是否需要使用代理 - 这很难看。
而不是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;
}