问题描述
我使用HTTP GET在浏览器中下载zip文件,例如(不是确切的网址)
I use HTTP GET that downloads a zip file in a browser, something like https://example.com/up/DBID/a/rRID/eFID/vVID (not the exact url)
现在,当我尝试对于桌面应用程序,在C#代码(与上述相同的GET方法)中进行相同的下载,下载的zip文件不是有效的归档文件。当我在记事本中打开这个文件时,它是一些HTML页面。
Now, when I try to do the same download in C# code(same GET method as above) for a desktop application, the zip file downloaded is not a valid archive file. When I opened this file in notepad, it was some HTML page.
我想我没有正确设置一些标题。我环顾四周。我发现有几个wrt上传,但没有看到任何下载。
I think I'm not setting some header correctly. I looked around for examples. I'd found several wrt uploads, but did not see anything for downloads.
代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/zip";
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default))
{
StreamWriter oWriter = new StreamWriter(@"D:\Downloads\1.zip");
oWriter.Write(sr.ReadToEnd());
oWriter.Close();
}
res.Close();
}
catch (Exception ex)
{
}
推荐答案
主要是因为您使用 StreamWriter:TextWriter
来处理二进制的Zip文件。 StreamWriter期望文本并将应用编码。即使简单的ASCII编码器也可能会尝试修复它认为是无效的行结尾。
It's mainly because you use a StreamWriter : TextWriter
to handle a binary Zip file. A StreamWriter expects text and will apply an Encoding. And even the simple ASCII Encoder might try to 'fix' what it thinks are invalid line-endings.
您可以用以下方式替换所有代码:
You can replace all your code with:
using (var client = new WebClient())
{
client.DownloadFile("http://something", @"D:\Downloads\1.zip");
}
这篇关于如何在C#中下载zip文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!