How do I download zip file in C#?

后端 未结 4 699
梦如初夏
梦如初夏 2020-12-17 10:56

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)

Now, when I try to do the sam

相关标签:
4条回答
  • 2020-12-17 11:03

    You could just use WebClient for a 2-liner:

    using(WebClient wc = new WebClient())
    {
       wc.DownloadFile(url, @"D:\Downloads\1.zip");
    }
    
    0 讨论(0)
  • 2020-12-17 11:03

    You can also use 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);
                      }
                 }
            }
    }
    
    0 讨论(0)
  • 2020-12-17 11:25

    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");
      }
    

    Note that for new code you should look at HttpClient instead of WebClient.
    And then don't use using( ) { }

    0 讨论(0)
  • Expanding on Ruben's answer which uses HttpClient instead of WebClient, you can add as an extension method like this:

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

    And then use like this:

    var archivePath = "https://api.github.com/repos/microsoft/winget-pkgs/zipball/";
    using (var httpClient = new HttpClient())
    {
        await httpClient.DownloadFile(archivePath, "./repo.zip");
    }
    
    0 讨论(0)
提交回复
热议问题