I'm trying to download zend-framework (from http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip) simply using WebClient

string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
WebClient downloader= new WebClient();
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");

The file is created, but it is empty. I checked response using fiddler and I get HTTP 200, correct content-length but "connection: closed" and fiddler shows "-1" in "body" column.

I have tried adding user agent (copied from google chrome request) and "connection: keep-alive" to headers, but none of these helped. I'm also pretty sure, that my program downloaded this file using the same URL once or twice before. There are no errors in events fired by WebClient.

Any ideas?

有帮助吗?

解决方案

Just my guess: maybe you can try to keep the WebClient instance in some place would not be garbage collected. When the DownloadFileCompleted event fired, you just clean the reference to the WebClient instance and let GC to reclaim the memory later (and don't forget to call Dispose method).

其他提示

Ok, I finnaly found the answer! Before downloading the file, I was checking its size by sending HttpWebRequest. The problem was, that i didn't Close() the response.

Thanks for the answers, they were nice clues.

Try to handle the DownloadProgressChanged and DownloadFileCompleted event.

private void button1_Click(object sender, EventArgs e)
  {
   string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
   WebClient downloader = new WebClient();
   downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted);
   downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
   downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
  }

 void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
   {
      label1.Text = e.BytesReceived + " " + e.ProgressPercentage;
    }
  void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
   {
       if (e.Error != null)
         MessageBox.Show(e.Error.Message);
       else
         MessageBox.Show("Completed!!!");
   }

If you have UAC enabled in Windows "C:\temp.zip" in the following line will fail to save the file because you aren't allowed to write outside of user directories without elevated permissions:

downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top