我正在使用webClient.DownloadFile()
下载一个文件,我可以为它设置一个超时,这样如果它不能访问文件,它就不会花太长时间吗?
发布于 2009-03-02 10:39:23
试试WebClient.DownloadFileAsync()
。您可以使用自己的超时时间通过计时器调用CancelAsync()
。
发布于 2010-06-16 18:57:14
我的答案来自here
您可以创建一个派生类,它将设置WebRequest
基类的timeout属性:
using System;
using System.Net;
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
您可以像使用基类WebClient一样使用它。
发布于 2014-01-26 02:37:20
假设您希望同步执行此操作,请使用WebClient.OpenRead(...)方法并在它返回的Stream上设置超时将会给出您想要的结果:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
从WebClient派生并覆盖GetWebRequest(...)@Beniamin建议设置超时,对我不起作用,但这确实起到了作用。
https://stackoverflow.com/questions/601861
复制相似问题