Try using the Async method and the events that go with it.
Something like this:
void Foo() {
var webClient = new WebClient();
var totalBytes = 0l;
var destFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "platform-tools-latest-windows.zip"));
webClient.DownloadProgressChanged += (s, e) => Debug.WriteLine($"Download progress changed: { e.ProgressPercentage }% ({ e.BytesReceived } / { (totalBytes = e.TotalBytesToReceive) })");
webClient.DownloadFileCompleted += (s, e) => {
destFile.Refresh();
if (destFile.Length != totalBytes) {
// Handle error
} else {
// Do nothing?
}
};
webClient.DownloadFileAsync(new Uri("https://dl.google.com/android/repository/platform-tools-latest-windows.zip"), destFile.FullName);
}
Give that a try and see if it works with your zip
EDIT:
If the above code doesn't work, there are a few more possibilities worth trying.
1: Try appending while (webClient.IsBusy);
to the end of the above method, to force the running thread to wait until the WebClient has finished downloading
2: Try downloading the raw data (byte[]
) first, then flushing the buffer to the file.
NOTE: ONLY DO THIS FOR SMALL(er) FILES!
public void DownloadFoo() {
var webClient = new WebClient();
var totalBytes = 0l;
var destFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "platform-tools-latest-windows.zip"));
webClient.DownloadProgressChanged += (s, e) => Debug.WriteLine($"Download progress changed: { e.ProgressPercentage }% ({ e.BytesReceived } / { (totalBytes = e.TotalBytesToReceive) })");
using (webClient) {
var buffer = webClient.DownloadData(new Uri("https://dl.google.com/android/repository/platform-tools-latest-windows.zip"));
using (var oStream = destFile.Open(FileMode.Truncate)) {
oStream.Write(buffer, 0, buffer.Length);
oStream.Flush(true); // true => flushToDisk
}
}
// webClient is automatically disposed of; method will return cleanly
}