简体   繁体   English

使用WebClient下载文件时出现异常(C#)

[英]Exception when downloading file using webclient (c#)

I'm using ac# code to download files from a website. 我正在使用ac#代码从网站下载文件。 I'm using the webclient class: 我正在使用webclient类:

using (var client = new WebClient())
{                    
    client.DownloadFile(
        @"http://www.cftc.gov/files/dea/history/com_disagg_txt_2018.zip",
        @"destination"
     );
}

The code worked fine for several weeks. 该代码可以正常工作几个星期。 But it ceased to work about a week ago. 但是大约一周前它停止工作了。 Whenever I run the code it throws an exception saying: 每当我运行代码时,它都会引发异常:

An existing connection was closed by the remote host. 远程主机已关闭现有连接。 (Error code 10054) (错误代码10054)

I was thinking that perhaps the website started to allow only download via browser so I added: 我在想,也许网站开始只允许通过浏览器下载,所以我补充道:

client.Headers["User-Agent"] ="Mozilla/5.0 (Windows NT 6.3; rv:36.0) 
Gecko/20100101 Firefox/36.0";

However, it did not resolve the issue. 但是,它没有解决问题。

Does anybody know a solution? 有人知道解决方案吗?

This failure is quite common. 这种失败很常见。
That Site has implemented TLS 1.2 protocol. 该站点已实施TLS 1.2协议。

The Protocol is switched to Https: even if you specified Http: in your URI. 即使您在URI中指定了Http: ,协议也会切换为Https:

You simply have to enable it, since .Net ServicePointManager (still) defaults to Ssl3/Tls 1.0 . 您只需启用它即可,因为.Net ServicePointManager (仍然)默认为Ssl3/Tls 1.0

Test it with this code: 使用以下代码对其进行测试:

string Url ="http://www.cftc.gov/files/dea/history/com_disagg_txt_2018.zip";

Uri URI = new Uri(Url, UriKind.Absolute);
WebClient_DownLoad(URI, FileName);


public void WebClient_DownLoad(Uri URI, string FileName)
{
    using (WebClient webclient = new WebClient())
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        webclient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
        webclient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
        webclient.Headers.Add(HttpRequestHeader.Accept, "ext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8");
        webclient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
        webclient.Headers.Add(HttpRequestHeader.KeepAlive, "keep-alive");
        webclient.UseDefaultCredentials = true;

        webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(WebClient_DownloadComplete);
        webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WebClient_DownloadProgress);

        webclient.DownloadFileAsync(URI, FileName);
    };
}

private void WebClient_DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
    string Result = string.Format("Received: {0}  Total: {1}  Percentage: {2}", 
                         e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
    //Update the UI
    Console.WriteLine(Result);
}

private static void WebClient_DownloadComplete(object sender, AsyncCompletedEventArgs e)
{
    if (!e.Cancelled)
    {
        if (e.Error != null)
            // Update the UI: transfer completed.
            Console.WriteLine("Error: " + e.Error.Message);

    }else{
        // Update the UI: transfer Cancelled.
        Console.WriteLine("Cancelled");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM