WebClient下载文件已损坏 [英] WebClient download file corrupted

查看:35
本文介绍了WebClient下载文件已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#WebClient下载文件。

以下是URL: http://www.czce.com.cn/cn/DFSStaticFiles/Future/2018/20180821/FutureDataClearParams.txt

如果我手动下载,一切都正常。但是,如果我使用WebClient下载文件,内容就会损坏。我尝试过使用许多不同的编码方法。以下是重现该问题的最小代码:

class Program
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        client.Proxy = new WebProxy("some company proxy");
        string url = "http://www.czce.com.cn/cn/DFSStaticFiles/Future/2018/20180821/FutureDataClearParams.txt";
        client.DownloadFile(url, @"D:file.txt");
    }
}

问题现在解决了,感谢大家的帮助(@Gauravsa,@John)。该文件确实是GZip格式的。

解决方案是:

public class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

推荐答案

使用WebClient.DownloadFile

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://www.czce.com.cn/cn/DFSStaticFiles/Future/2018/20180821/FutureDataClearParams.txt", 
                        @"c:UsersJonTestfoo.txt");
}

using (WebClient client = new WebClient())
{
        client.DownloadFile("http://www.czce.com.cn/cn/DFSStaticFiles/Future/2018/20180821/FutureDataClearParams.txt", 
                            "c:\Users\Jon\Test\foo.txt");
}

您可以执行其他文件I/O操作,如

if(!Directory.Exists("c:\Users\Jon\Test\")
    Directory.CreateDirectory("c:\Users\Jon\Test\");

...

这篇关于WebClient下载文件已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆