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下载文件已损坏


猜你喜欢
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01