嘗試使用異步方法和與之一起使用的事件。 事情是這樣的:
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);
}
給一個嘗試,看看它是否與您的郵遞工作
編輯: 如果上面的代碼不能正常工作,有一些更多的可能性值得嘗試。
1:嘗試附加while (webClient.IsBusy);
上述方法結束時,強制運行的線程等待,直到Web客戶端下載完
2:嘗試第一下載的原始數據(byte[]
),然後沖洗緩衝到文件。
注意:只能做這個小(呃)文件!
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
}
你從哪裏下載?您自己設計的公共資源或自定義應用程序? – DiskJunky
@DiskJunky這是一個公共資源,但我不能共享URL,因爲它只是內部使用。 – Sam
對於解壓縮部分:https://stackoverflow.com/questions/836736/unzip-files-programmatically-in-net?rq=1 – Goufalite