【发布时间】:2010-10-10 18:04:59
【问题描述】:
我正在使用webClient.DownloadFile() 下载文件,我可以为此设置一个超时时间,以便它无法访问该文件时不会花费很长时间?
【问题讨论】:
标签: c# .net download webclient
我正在使用webClient.DownloadFile() 下载文件,我可以为此设置一个超时时间,以便它无法访问该文件时不会花费很长时间?
【问题讨论】:
标签: c# .net download webclient
试试WebClient.DownloadFileAsync()。您可以使用自己的超时时间通过计时器调用CancelAsync()。
【讨论】:
var taskDownload = client.DownloadFileTaskAsync(new Uri("http://localhost/folder"),"filename")然后taskDownload.Wait(TimeSpan.FromSeconds(5));
我的回答来自here
您可以创建一个派生类,它将设置基类WebRequest 的超时属性:
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 类一样使用它。
【讨论】:
request.Timeout 这一行收到错误。错误消息'System.Net.WebRequest' does not contain a definition for 'Timeout' and no extension method 'Timeout' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?) ,我错过了什么?
using 指令。
假设您想同步执行此操作,使用 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 建议的超时,这对我不起作用,但确实如此。
【讨论】:
stream.ReadTimeout 大于执行请求的实际时间,我仍然会收到 WebException 说“请求已中止 - 操作已超时”