win8 metro HttpClient下载文件-带进度条

HttpClient 直接下载文件,如果文件比较大,没有进度显示会很不友好,

所有在下载的时候希望下载一部分就显示一下进度。

代码的重点是

HttpCompletionOption.ResponseHeadersRead
以及
ReadAsStreamAsync

对于dispose,也可以用using。

var saveFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename,
                        CreationCollisionOption.ReplaceExisting);
                    var fs = await saveFile.OpenAsync(FileAccessMode.ReadWrite);
                    HttpClientHandler handler = new HttpClientHandler();
                    handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                    HttpClient hc = new HttpClient(handler);
                    HttpResponseMessage response = await hc.GetAsync(DownUrl, HttpCompletionOption.ResponseHeadersRead);
                    Stream stream = await response.Content.ReadAsStreamAsync();
                    IInputStream inputStream = stream.AsInputStream();
                    ulong totalBytesRead = 0;
                    while (true)
                    {
                        // Read from the web.
                        IBuffer buffer = new Buffer(1024);
                        buffer = await inputStream.ReadAsync(
                            buffer,
                            buffer.Capacity,
                            InputStreamOptions.None);

                        if (buffer.Length == 0)
                        {
                            // 完成
                            break;
                        }

                        // 进度
                        totalBytesRead += buffer.Length;
                        System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);

                        // 写文件.
                        await fs.WriteAsync(buffer);
                    }
                    inputStream.Dispose();
                    fs.Dispose();


win8 metro HttpClient下载文件-带进度条,布布扣,bubuko.com

win8 metro HttpClient下载文件-带进度条

上一篇:基于Windows Server 2003 ntbackup下数据文件的完整备份与差异备份


下一篇:Win XP 之 XAMPP安装及配置