WebClient download file corrupted(WebClient下载文件已损坏)
本文介绍了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下载文件已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:WebClient下载文件已损坏
基础教程推荐
猜你喜欢
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01