我需要下载一些大文件,所以我需要比默认的1分钟更长的DownloadFile()超时时间。
问题是我的解决方案没有增加超时时间。它停留在1分钟。
我创建了这个类:
public class MyWebClient : WebClient
{
private int timeout;
public int Timeout
{
get
{
return timeout;
}
set
{
timeout = value;
}
}
public MyWebClient()
{
this.timeout = 1200000;
}
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = this.timeout;
return w;
}
}
这样称呼它:
using (MyWebClient client = new MyWebClient())
{
client.Timeout = 1200000;
client.DownloadFile(new Uri(fileUrl), localFile);
}
有什么想法吗?
在客户端请求中尝试此代码
using (MyWebClient client = new MyWebClient())
{
client.Timeout = 1200000;
byte[] data = client.DownloadData(url);
File.WriteAllBytes(localFile, data);
}
将您的代码更改为以下
private class MyWebClient : WebClient
{
public int Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = Timeout;
((HttpWebRequest) w).ReadWriteTimeout = Timeout;
return w;
}
}
按照你提到的打电话。
更新时间:--其他明智的用途如下
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
req.Timeout = 1200000;
req.ReadWriteTimeout = 1200000;
var w = (HttpWebResponse)req.GetResponse();
using (Stream file = File.OpenWrite(localFile))
{
w.GetResponseStream().CopyTo(file);
}