93

我正在webClient.DownloadFile()用来下载文件,我可以为此设置一个超时时间,这样如果它无法访问该文件就不会花费这么长时间吗?

4

3 回答 3

260

我的答案来自这里

您可以创建一个派生类,它将设置基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 类一样使用它。

于 2010-06-16T10:57:13.760 回答
42

试试WebClient.DownloadFileAsync()。您可以CancelAsync()使用自己的超时时间通过计时器调用。

于 2009-03-02T10:39:22.760 回答
3

假设您想同步执行此操作,使用 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 建议的超时,这对我不起作用,但确实如此。

于 2014-01-25T18:37:20.013 回答