如何在C#中下载zip文件?

时间:2011-01-22 16:28:43

标签: c# http get download

我使用HTTP GET在浏览器中下载zip文件,例如https://example.com/up/DBID/a/rRID/eFID/vVID(不是确切的网址)

现在,当我尝试在桌面应用程序中使用C#代码(与上面相同的GET方法)进行相同的下载时,下载的zip文件不是有效的存档文件。当我在记事本中打开此文件时,它是一些HTML页面。

我想我没有正确设置一些标题。我四处寻找例子。我发现了几个wrt上传,但没有看到任何下载。

代码:

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)
{
}

4 个答案:

答案 0 :(得分:38)

这主要是因为您使用StreamWriter : TextWriter来处理二进制Zip文件。 StreamWriter需要文本并将应用编码。甚至简单的ASCII编码器也可能试图“修复”它认为无效的行结尾。

您可以将所有代码替换为:

  using (var client = new WebClient())
  {
    client.DownloadFile("http://something",  @"D:\Downloads\1.zip");
  }

答案 1 :(得分:7)

你可以使用WebClient作为2-liner:

using(WebClient wc = new WebClient())
{
   wc.DownloadFile(url, @"D:\Downloads\1.zip");
}

答案 2 :(得分:0)

您还可以使用System.Net.Http.HttpClient

using (HttpClient client = new HttpClient())
{
        using (HttpResponseMessage response = await client.GetAsync(downloadURL))
        {
             using(var stream = await response.Content.ReadAsStreamAsync())
             {
                  using(Stream zip = FileManager.OpenWrite(ZIP_PATH))
                  {
                       stream.CopyTo(zip);
                  }
             }
        }
}

答案 3 :(得分:0)

扩展使用HttpClient instead of WebClient的鲁宾答案,您可以添加如下扩展方法:

using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public static class Extensions
{
    public static async Task DownloadFile (this HttpClient client, string address, string fileName) {
        using (var response = await client.GetAsync(address))
        using (var stream = await response.Content.ReadAsStreamAsync())
        using (var file = File.OpenWrite(fileName)) {
            stream.CopyTo(file);
        }
    }
}

然后像这样使用:

var archivePath = "https://api.github.com/repos/microsoft/winget-pkgs/zipball/";
using (var httpClient = new HttpClient())
{
    await httpClient.DownloadFile(archivePath, "./repo.zip");
}