簡體   English   中英

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

[英]How do I download zip file in C#?

我使用 HTTP GET 在瀏覽器中下載一個 zip 文件,類似於https://example.com/up/DBID/a/rRID/eFID/vVID (不是確切的 url)

現在,當我嘗試用 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)
{
}

這主要是因為您使用StreamWriter : TextWriter來處理二進制 Zip 文件。 StreamWriter 需要文本並將應用編碼。 即使是簡單的 ASCII 編碼器也可能會嘗試“修復”它認為無效的行尾。

您可以將所有代碼替換為:

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

請注意,對於新代碼,您應該查看 HttpClient 而不是 WebClient。
然后不要使用using( ) { }

您可以將WebClient用於 2-liner:

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

您還可以使用 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);
                  }
             }
        }
}

擴展魯本使用HttpClient 而不是 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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM