如何更改 .NET WebClient 对象的超时时间

问题描述:

我正在尝试将客户端的数据(以编程方式)下载到我的本地计算机,而他们的网络服务器非常非常慢,这导致我的 WebClient 对象超时.

I am trying to download a client's data to my local machine (programatically) and their webserver is very, very slow which is causing a timeout in my WebClient object.

这是我的代码:

WebClient webClient = new WebClient();

webClient.Encoding = Encoding.UTF8;
webClient.DownloadFile(downloadUrl, downloadFile);

有没有办法在这个对象上设置无限超时?或者,如果没有,任何人都可以帮我举一个替代方法的例子吗?

Is there a way to set an infinite timeout on this object? Or if not can anyone help me with an example on an alternate way to do this?

该 URL 在浏览器中运行良好 - 显示大约需要 3 分钟.

The URL works fine in a browser - it just takes about 3 minutes to show.

您可以延长超时时间:继承原始 WebClient 类并覆盖 webrequest getter 以设置您自己的超时时间,如下例所示.

You can extend the timeout: inherit the original WebClient class and override the webrequest getter to set your own timeout, like in the following example.

在我的例子中,MyWebClient 是一个私有类:

MyWebClient was a private class in my case:

private class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = 20 * 60 * 1000;
        return w;
    }
}