WebClient 下载文件损坏

WebClient download file corrupted

我正在尝试使用 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)。该文件确实是 GZipped。

解决方法是:

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

我测试它并工作。

例如,看看这个控制台应用程序。它从 URL 下载您的文件,并将其作为 file.txt 保存到桌面。 :

class Program
{
    static void Main(string[] args)
    {
    WebClient client = new WebClient();
                string address = "http://www.czce.com.cn/cn/DFSStaticFiles/Future/2018/20180821/FutureDataClearParams.txt";
                // Save the file to desktop for debugging
                var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string fileName = desktop + "\file.txt";
                client.DownloadFile(address, fileName);
    }
}

使用WebClient.DownloadFile:

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

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\");

...