如何在 C# 中下载 zip 文件? [英] How do I download zip file in C#?
问题描述
我使用 HTTP GET 在浏览器中下载 zip 文件,例如 https://example.com/up/DBID/a/rRID/eFID/vVID(不是确切的网址)
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:Downloads1.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:Downloads1.zip");
}
注意对于新代码,您应该查看 HttpClient 而不是 WebClient.
然后不要使用 using( ) { }
Note that for new code you should look at HttpClient instead of WebClient.
And then don't use using( ) { }
这篇关于如何在 C# 中下载 zip 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!