I want to download a ZIP file from some web URL. When I open the browser and write the URL, the browser directly start downloading the ZIP file. However what I want is to automate this using C# code.
I have tried the following code:
private void btnDownload_Click(object sender, EventArgs e) {
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadFileAsync(new Uri("http://---/file.zip"), @"c:\file.zip");
}
private void Completed(object sender, AsyncCompletedEventArgs e) {
MessageBox.Show("Download completed!");
}
It seems that the download is working, but when I check the downloaded file I find it as 0 KB.
Any idea what's going on?
This works:
As I can see, your code corresponds to known antipattern Timer and Garbage Collector.
When
btnDownload_Click
is finished, thewebClient
variable becomes unreachable, and the garbage collector destroys it together with its functionality.Try this:
Now `webClient is the member of the class and is reachable. Then the garbage collector will not destroy it.
Full Example: Full sample at .Net Fiddle
You could easily use the ZipFile class like this:
Please note that this is only available from .Net Framework version 4.5 onwards..
I also had this problem, but I found a simple solution i want to Download this Zip File from "http://sodco.ir/Choobkhat/Update/update.zip" and extract them. but webClient not Download it.
My Solution:
Step 1: change my FileName from "D:\update.zip" to "D:\update.zi"
webClient.DownloadFileAsync("http://sodco.ir/Choobkhat/Update/update.zip", "D:\\update.zi);
It will start downloading,After the download is completed:
Step 2: Rename update.zi to update.zip
File.Move("update.zi", "update.zip");
Step 3: extract them
Refrence