Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download zip file in C#?

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 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.

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.

Code:

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)
{
}
like image 619
Merrin Avatar asked Jan 22 '11 16:01

Merrin


People also ask

How do I download a zip file?

A ZIP file is a container for other files. ZIP files compress their contents, which reduces downloading time. To download a ZIP file, click on a link to it; this will prompt your browswer to ask you if you would like to open or save the file. Select Save.

How do I download a ZIP file from Google?

Open up Google Drive on your computer and sign into your Google account. 2. Scroll to the Folders section and find the folder you want to download. Right-click on the folder, then select Download towards the bottom.

Why is downloading zip file so slow?

zip files from untrusted websites (such as websites without security certificates, websites with expired security certificates, or websites with certificates issued by non-authorized organizations) when they are downloaded. This result in slow file download.


2 Answers

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

like image 193
Henk Holterman Avatar answered Oct 28 '22 00:10

Henk Holterman


You could just use WebClient for a 2-liner:

using(WebClient wc = new WebClient())
{
   wc.DownloadFile(url, @"D:\Downloads\1.zip");
}
like image 44
BrokenGlass Avatar answered Oct 27 '22 22:10

BrokenGlass