Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

http - 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:Downloads1.zip");
        oWriter.Write(sr.ReadToEnd());
        oWriter.Close();
    }
    res.Close();
}
catch (Exception ex)
{
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...