C# 为 webClient.DownloadFile() 设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/601861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:53:13  来源:igfitidea点击:

Set timeout for webClient.DownloadFile()

c#.netdownloadwebclient

提问by UnkwnTech

I'm using webClient.DownloadFile()to download a file can I set a timeout for this so that it won't take so long if it can't access the file?

我正在使用webClient.DownloadFile()下载文件,我可以为此设置超时,以便在无法访问文件时不会花费很长时间吗?

采纳答案by abatishchev

Try WebClient.DownloadFileAsync(). You can call CancelAsync()by timer with your own timeout.

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

回答by Beniamin

My answer comes from here

我的答案来自这里

You can make a derived class, which will set the timeout property of the base WebRequestclass:

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

and you can use it just like the base WebClient class.

您可以像使用基本 WebClient 类一样使用它。

回答by jeffrymorris

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

假设您想同步执行此操作,使用 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);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

从 WebClient 派生并覆盖 GetWebRequest(...) 以设置 @Beniamin 建议的超时,对我来说不起作用,但确实如此。