我正在编写一个图书馆,意图在桌面(.Net 4.0及更高版本),手机(WP 7.5及以上版本)和
Windows Store(Windows 8及更高版本)应用程序中使用它.
该库能够使用Portable HttpClient库从Internet下载文件,并报告下载进度.
解决方法
我编写了以下代码来实现进度报告.代码支持我想要的所有平台;但是,您需要引用以下NuGet包:
> Microsoft.Net.Http
> Microsoft.Bcl.Async
这是代码:
public async Task DownloadFileAsync(string url,IProgress<double> progress,CancellationToken token) { var response = await client.GetAsync(url,HttpCompletionOption.ResponseHeadersRead,token); if (!response.IsSuccessStatusCode) { throw new Exception(string.Format("The request returned with HTTP status code {0}",response.StatusCode)); } var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; var canReportProgress = total != -1 && progress != null; using (var stream = await response.Content.ReadAsStreamAsync()) { var totalRead = 0L; var buffer = new byte[4096]; var isMoreToRead = true; do { token.ThrowIfCancellationRequested(); var read = await stream.ReadAsync(buffer,buffer.Length,token); if (read == 0) { isMoreToRead = false; } else { var data = new byte[read]; buffer.ToList().CopyTo(0,data,read); // TODO: put here the code to write the file to disk totalRead += read; if (canReportProgress) { progress.Report((totalRead * 1d) / (total * 1d) * 100); } } } while (isMoreToRead); } }
使用它很简单:
var progress = new Microsoft.Progress<double>(); progress.ProgressChanged += (sender,value) => System.Console.Write("\r%{0:N0}",value); var cancellationToken = new CancellationTokenSource(); await DownloadFileAsync("http://www.dotpdn.com/files/Paint.NET.3.5.11.Install.zip",progress,cancellationToken.Token);