尝试使用WebClient.DownloadFile()或WebRequest下载文件时无法实现超时

nrnfms

我正在尝试实现一些从URL下载文件的功能。但是,如果文件花费的时间超过30秒,我想取消下载或使其超时。

我尝试重写WebClient类以实现超时,但是无论我将超时设置为什么值,它都永远不会超时!这是我尝试过的代码,可在另一个stackoverflow答案中找到

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;
    }
}

然后,使用调用:

 WebDownload webClient = new WebDownload(20000);
 try 
 {               
      webClient.DownloadFile(url, tmpFile);
 }
 catch {
     //throw error
 }

我也尝试过使用WebRequest方法下载文件,并使用Timeout和ReadWriteTimeout属性,但是没有骰子。必须是一个非常普遍的用例。任何帮助表示赞赏。谢谢!

克尔齐耶克·布罗纳克

您实现的超时关系到获取Response,而不是响应Stream,因为它包含所有数据并且通常花费更多时间来实现。例如,获取响应通常需要不到1秒,但是下载网页内容可能需要几秒钟。

至于下载文件,您可以使用HttpWebRequestgetHttpWebResponse方法和从中使用use方法GetResponseStream()将流获取到数据。

这将是有帮助的:HttpWebResponse的编码问题

尤其byte[] buffer是用于获取数据部分而不是StreamReader ReadToEnd()方法的部分。在下载部分数据以缓冲时,您可以对照超时日期时间检查当前日期时间,从而允许在其之后取消下载。

编辑:一段有用的代码

private byte[] DownloadFile( string uri, int requestTimeout, int downloadTimeout, out bool isTimeout, out int bytesDownloaded )
{
    HttpWebRequest request = WebRequest.Create( uri ) as HttpWebRequest;
    request.Timeout = requestTimeout;
    HttpWebResponse response = null;
    Stream responseStream = null;
    MemoryStream downloadedData = null;

    byte[] result = null;
    bytesDownloaded = 0;

    isTimeout = false;
    try
    {
        // Get response
        response = request.GetResponse() as HttpWebResponse;
        byte[] buffer = new byte[ 16384 ];

        // Create buffer for downloaded data
        downloadedData = new MemoryStream();

        // Set the timeout
        DateTime timeout = DateTime.Now.Add( new TimeSpan( 0, 0, 0, 0, downloadTimeout ) );

        // Read parts of the stream
        responseStream = response.GetResponseStream();
        int bytesRead = 0;
        DateTime now = DateTime.Now;
        while ( (bytesRead = responseStream.Read( buffer, 0, buffer.Length )) > 0 && DateTime.Now < timeout )
        {
            downloadedData.Write( buffer, 0, bytesRead );
            now = DateTime.Now;
            bytesDownloaded += bytesRead;
        }

        // Notify if timeout occured (could've been written better)
        if ( DateTime.Now >= timeout )
        {
            isTimeout = true;
        }
    }
    catch ( WebException ex )
    {
        // Grab timeout exception
        if ( ex.Status == WebExceptionStatus.Timeout )
        {
            isTimeout = true;
        }
    }
    finally
    {
        // Close the stream
        if ( responseStream != null )
        {
            responseStream.Close();
        }
    }

    if ( downloadedData != null )
    {
        result = downloadedData.GetBuffer();
        downloadedData.Close();
    }

    return result;
}

用法

private void button1_Click( object sender, EventArgs e )
{
    bool isTimeout;
    int bytesDownloaded;
    byte[] data = DownloadFile( something, 1000,500, out isTimeout, out bytesDownloaded );

    MessageBox.Show( "Downloaded " + bytesDownloaded.ToString() + " bytes, Timeout = " + isTimeout.ToString() );
}

请记住,此代码仍然容易受到您可能遇到的其他异常的影响。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

尝试使用WebClient.DownloadFile()或WebRequest下载文件时无法实现超时

来自分类Dev

尝试使用WebClient下载文件时遇到重定向重定向的问题

来自分类Dev

无法使用WebClient.DownloadFile方法从启用了TLS 1.1 / 1.2协议的计算机上下载文件

来自分类Dev

c#尝试使用WebClient下载文件名中包含特殊字符的文件

来自分类Dev

使用WebClient从https下载文件时出错

来自分类Dev

使用WebClient POST查询并下载文件

来自分类Dev

使用c#WebClient下载文件

来自分类Dev

使用WebClient POST查询并下载文件

来自分类Dev

尝试使用.NET WebClient下载响应时出现“无法解析远程名称”异常

来自分类Dev

WebClient超时花费比预期更长的时间(使用:接收,尝试捕获,任务)

来自分类Dev

使用通配符通过Invoke-WebRequest下载文件

来自分类Dev

初次使用后无法重用WebClient吗?尝试重置页眉,不起作用

来自分类Dev

尝试使用FileUtils下载文件

来自分类Dev

Vertx WebClient 下载文件

来自分类Dev

无法通过ASP.NET Core中的WebClient.DownloadFile方法下载日志文件

来自分类Dev

使用WebClient设置超时

来自分类Dev

从https URL下载文件时出现WebClient错误

来自分类Dev

当从 VSTS 下载带有画布的 docx 文件时,WebClient DownloadFile 不起作用

来自分类Dev

尝试下载CQ依赖罐时,保管库命令给出“无法挂载文件系统”

来自分类Dev

无法使用PHP强制下载文件

来自分类Dev

无法使用Selenium WebDriver下载文件

来自分类Dev

无法使用ChromeDriver下载文件

来自分类Dev

无法使用wget下载文件

来自分类Dev

使用 WebClient 下载文件时出现异常不支持并发 I/O 操作如何解决?

来自分类Dev

使用Google Picker API后尝试下载文件时出现错误401

来自分类Dev

当我尝试强制使用php下载文件时出现错误

来自分类Dev

尝试使用获取 AttributeError 的 Python FTP_TLS 对象下载文件时?

来自分类Dev

尝试下载文件时未找到该网址的网页

来自分类Dev

无法使用javascript设置下载文件的下载名称

Related 相关文章

  1. 1

    尝试使用WebClient.DownloadFile()或WebRequest下载文件时无法实现超时

  2. 2

    尝试使用WebClient下载文件时遇到重定向重定向的问题

  3. 3

    无法使用WebClient.DownloadFile方法从启用了TLS 1.1 / 1.2协议的计算机上下载文件

  4. 4

    c#尝试使用WebClient下载文件名中包含特殊字符的文件

  5. 5

    使用WebClient从https下载文件时出错

  6. 6

    使用WebClient POST查询并下载文件

  7. 7

    使用c#WebClient下载文件

  8. 8

    使用WebClient POST查询并下载文件

  9. 9

    尝试使用.NET WebClient下载响应时出现“无法解析远程名称”异常

  10. 10

    WebClient超时花费比预期更长的时间(使用:接收,尝试捕获,任务)

  11. 11

    使用通配符通过Invoke-WebRequest下载文件

  12. 12

    初次使用后无法重用WebClient吗?尝试重置页眉,不起作用

  13. 13

    尝试使用FileUtils下载文件

  14. 14

    Vertx WebClient 下载文件

  15. 15

    无法通过ASP.NET Core中的WebClient.DownloadFile方法下载日志文件

  16. 16

    使用WebClient设置超时

  17. 17

    从https URL下载文件时出现WebClient错误

  18. 18

    当从 VSTS 下载带有画布的 docx 文件时,WebClient DownloadFile 不起作用

  19. 19

    尝试下载CQ依赖罐时,保管库命令给出“无法挂载文件系统”

  20. 20

    无法使用PHP强制下载文件

  21. 21

    无法使用Selenium WebDriver下载文件

  22. 22

    无法使用ChromeDriver下载文件

  23. 23

    无法使用wget下载文件

  24. 24

    使用 WebClient 下载文件时出现异常不支持并发 I/O 操作如何解决?

  25. 25

    使用Google Picker API后尝试下载文件时出现错误401

  26. 26

    当我尝试强制使用php下载文件时出现错误

  27. 27

    尝试使用获取 AttributeError 的 Python FTP_TLS 对象下载文件时?

  28. 28

    尝试下载文件时未找到该网址的网页

  29. 29

    无法使用javascript设置下载文件的下载名称

热门标签

归档