UWP 下载文件显示下载进度
<Page
x:Class="WgscdProject.TestDownloadPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WgscdProject"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid Name="d">
<TextBlock Name="txt2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,-164,0,0" Text="file path"></TextBlock>
<TextBlock Name="txt" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,-84,0,0" Text="100%"></TextBlock>
<Grid Name="gridPercent" Background="WhiteSmoke" Height="22">
<Rectangle Name="lbPercent" Fill="Blue" Width="1" HorizontalAlignment="Left" Height="22"></Rectangle>
</Grid>
<Button VerticalAlignment="Top" Height="55" Width="222" HorizontalAlignment="Center" Content="test download" Click="Button_Click"></Button>
</Grid> </Page> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace WgscdProject
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class TestDownloadPage : Page
{
public TestDownloadPage()
{
this.InitializeComponent(); worker = new BackgroundWorker();
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); ;
worker.DoWork += new DoWorkEventHandler(worker_DoWork); } BackgroundWorker worker;
bool isDownloading = false;
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ } void worker_DoWork(object sender, DoWorkEventArgs e)
{
dowloadFile();
} public async void Invoke(Action action, Windows.UI.Core.CoreDispatcherPriority Priority = Windows.UI.Core.CoreDispatcherPriority.Normal) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Priority, () => { action(); }); } async void dowloadFile()
{ if (isDownloading) return; isDownloading = true ;
string serverUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";//"https://files.cnblogs.com/files/wgscd/jyzsUpdate.zip"; try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(serverUrl);
System.Net.WebResponse response = await request.GetResponseAsync(); System.IO.Stream ns = response.GetResponseStream();
long totalSize = response.ContentLength;
double hasDownSize = 0;
byte[] nbytes = new byte[512];//521,2048 etc
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, nbytes.Length);
StorageFolder folder;
folder = ApplicationData.Current.LocalFolder; // await StorageFolder.GetFolderFromPathAsync("F:\\");
string localFile = "1.rar";
StorageFile file = await folder.CreateFileAsync(localFile, CreationCollisionOption.ReplaceExisting); using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
while (nReadSize > 0)
{ dataWriter.WriteBytes(nbytes); nReadSize = ns.Read(nbytes, 0, 512);
hasDownSize += nReadSize;
this.Invoke(new Action(() =>
{
txt.Text = "" + (hasDownSize /1024.0).ToString("0.00")+ " KB/" +( totalSize / 1024.0).ToString("0.00") + " KB (" + (((double)hasDownSize * 100 / totalSize).ToString("0")) + "%)";//显示下载百分比
lbPercent.Width = gridPercent.RenderSize.Width * ((double)hasDownSize / totalSize);
txt.UpdateLayout();
})); } transaction.Stream.Size = await dataWriter.StoreAsync();
await dataWriter.FlushAsync ();
await transaction.CommitAsync(); this.Invoke(new Action(() =>
{
txt.Text = "100%";//显示下载百分比
txt.UpdateLayout();
}));
// MessageBox.Show("下载完成"); }
} }
catch (Exception ex)
{
// fs.Close();
new MessageDialog("出现错误:" + ex.ToString()).ShowAsync();
} isDownloading = false;
} private void Button_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
}
}
}
UWP 下载文件显示下载进度的更多相关文章
- VC下载文件显示进度条
VC下载文件显示进度条 逗比汪星人2009-09-18上传 by Koma http://blog.csd.net/wangningyu http://download.csdn.net/deta ...
- AsyncTask用法解析-下载文件动态更新进度条
1. 泛型 AysncTask<Params, Progress, Result> Params:启动任务时传入的参数,通过调用asyncTask.execute(param)方法传入. ...
- Handler实现线程之间的通信-下载文件动态更新进度条
1. 原理 每一个线程对应一个消息队列MessageQueue,实现线程之间的通信,可通过Handler对象将数据装进Message中,再将消息加入消息队列,而后线程会依次处理消息队列中的消息. 2. ...
- VC下载文件 + 显示进度条
在codeproject里找了许久,发现这样一个VC下载文件并显示进度条的源码,于是添加了些中文注释: 1.下载线程函数: UINT DownloadFile(LPVOID pParam) { CWn ...
- winform 下载文件显示进度和百分比
/// <summary> /// 下载完成 /// </summary> private void DownloadFileCompleted() { IsComlate = ...
- WPF多线程下载文件,有进度条
//打开对话框选择文件 private void OpenDialogBox_Click(object sender, RoutedEventArgs e) { ...
- AFHTTPSessionManager下载文件 及下载中 进度条处理,进度条处理需要特别注意,要加载NSRunLoop 中
1.下载文件 和进度条处理代码 - (void)timer:(NSTimer *)timer{ // 另一个View中 进度条progress属性赋值 _downloadView.progress = ...
- dotnet 通过 HttpClient 下载文件同时报告进度的方法
本文告诉大家一个简单的方法通过 HttpClient 下载文件,同时报告下载进度 通过 HttpClient 的 ContentLength 很多时候都可以拿到下载的内容的长度,通过 ReadAsyn ...
- c#导出文件,下载文件,命名下载后的文件名
Page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpU ...
随机推荐
- FI配置清单-概要
1.编辑公司代码 T-Code:OX02 路径:IMG >企业结构Enterprise >定义Definition >财务会计 Financial Accounting>编辑, ...
- TensorFlow Saver 保存最佳模型 tf.train.Saver Save Best Model
TensorFlow Saver 保存最佳模型 tf.train.Saver Save Best Model Checkmate is designed to be a simple drop-i ...
- 【Java入门提高篇】Day4 Java中的回调
又忙了一周,事情差不多解决了,终于有可以继续写我的博客了(各位看官久等了). 这次我们来谈一谈Java里的一个很有意思的东西——回调. 什么叫回调,一本正经的来讲,在计算机程序设计中,回调函数是指通过 ...
- redis学习历程
redis只知道作用于缓存,其它一无所知,所以现在系统的 学习下,这样应用的时候可以考虑多面性和实用性 首先先了解一下redis的背景和概念 背景 Redis是一个开源的使用ANSI C语言编写.支持 ...
- hashlib 简单的登录例子
hashlib例子: =============================================== import hashlib md5 = hashlib.md5() md5.up ...
- c# 二分查找法
1.仅 当 列表 是 有序 的 时候, 二分 查找 才 管用. 2.一般而言, 对于 包含 n 个 元素 的 列表, 用 二分 查找 最多 需要 log2n 步, 而 简单 查找 最多 需要 n 步. ...
- MySQL复制 slave_exec_mode 参数IDEMPOTENT 说明
背景: 今天无意当中看到参数slave_exec_mode,从手册里的说明看出该参数和MySQL复制相关,是可以动态修改的变量,默认是STRICT模式(严格模式),可选值有IDEMPOTENT模式 ...
- MongoDB基础之 安装
本篇来介绍MongoDB的安装.安装版本是3.4.18 如果安装老版本的mongodb,你会发现安装比较顺利,但是新版本的mongo安装稍微麻烦一点 ,主要是多了安全机制认证等步骤. 1.下载mong ...
- Android Handler 内存泄漏,文末消息机制的小总结
1. 内存泄漏的Activity public class MainActivity extends AppCompatActivity { private static final int MESS ...
- kudu基础入门
1.kudu介绍 1.1 背景介绍 在KUDU之前,大数据主要以两种方式存储: (1)静态数据: 以 HDFS 引擎作为存储引擎,适用于高吞吐量的离线大数据分析场景.这类存储的局限性是数据无法进行随机 ...