<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 下载文件显示下载进度的更多相关文章

  1. VC下载文件显示进度条

    VC下载文件显示进度条 逗比汪星人2009-09-18上传   by Koma http://blog.csd.net/wangningyu http://download.csdn.net/deta ...

  2. AsyncTask用法解析-下载文件动态更新进度条

    1. 泛型 AysncTask<Params, Progress, Result> Params:启动任务时传入的参数,通过调用asyncTask.execute(param)方法传入. ...

  3. Handler实现线程之间的通信-下载文件动态更新进度条

    1. 原理 每一个线程对应一个消息队列MessageQueue,实现线程之间的通信,可通过Handler对象将数据装进Message中,再将消息加入消息队列,而后线程会依次处理消息队列中的消息. 2. ...

  4. VC下载文件 + 显示进度条

    在codeproject里找了许久,发现这样一个VC下载文件并显示进度条的源码,于是添加了些中文注释: 1.下载线程函数: UINT DownloadFile(LPVOID pParam) { CWn ...

  5. winform 下载文件显示进度和百分比

    /// <summary> /// 下载完成 /// </summary> private void DownloadFileCompleted() { IsComlate = ...

  6. WPF多线程下载文件,有进度条

    //打开对话框选择文件         private void OpenDialogBox_Click(object sender, RoutedEventArgs e)         {     ...

  7. AFHTTPSessionManager下载文件 及下载中 进度条处理,进度条处理需要特别注意,要加载NSRunLoop 中

    1.下载文件 和进度条处理代码 - (void)timer:(NSTimer *)timer{ // 另一个View中 进度条progress属性赋值 _downloadView.progress = ...

  8. dotnet 通过 HttpClient 下载文件同时报告进度的方法

    本文告诉大家一个简单的方法通过 HttpClient 下载文件,同时报告下载进度 通过 HttpClient 的 ContentLength 很多时候都可以拿到下载的内容的长度,通过 ReadAsyn ...

  9. c#导出文件,下载文件,命名下载后的文件名

    Page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpU ...

随机推荐

  1. 2.Hibernate的主配置文件hibernate.cfg.xml

    1.配置 Hibernate 需要事先知道在哪里找到映射信息,这些映射信息定义了 Java 类怎样关联到数据库表.Hibernate 也需要一套相关数据库和其它相关参数的配置设置.所有这些信息通常是作 ...

  2. 详解Oracle DELETE和TRUNCATE 的区别

    原文地址:http://www.cnblogs.com/simplefrog/archive/2012/07/30/2615169.html 语法delete from aa truncate tab ...

  3. 《SQL Server 2008从入门到精通》--20180716

    1.锁 当多个用户同时对同一个数据进行修改时会产生并发问题,使用事务就可以解决这个问题.但是为了防止其他用户修改另一个还没完成的事务中的数据,就需要在事务中用到锁. SQL Server 2008提供 ...

  4. 【mpu6050】学习笔记——基础知识点记录

    如图: 假设为三维空间有一个向量R 满足关系:  即为加速度计的x轴,y轴,z轴. 对于MPU6050 其求出的数值为:    分母为灵敏度, ADCRx为读出值. 我关心的是Axr,Ayr,Azr即 ...

  5. Linux运维之——每日小技巧,获取网站请求数的前20个IP

    获取网站请求书的前20个IP |grep tcp|awk '{print $5}'|awk -F: '{print $1}'|sort|uniq -c|sort -nr|head -n20

  6. python + pyqt5 QlineEdit QMessageBox实现信息录入和消息弹框提醒

    本人现在在做自动化工具开发的工作,因此,记录下自己平时遇到的问题和解决之道,还有一些简单的小工具 以下为主代码 # --*-- coding:utf-8 --*-- from first import ...

  7. centos中,tomcat项目创建文件的权限

    参考文章:https://cloud.tencent.com/info/5f02caa932fd6dbfc46a3bb01af135e0.html 我们在centos中输入umask,会看到输出002 ...

  8. Docker容器学习与分享03

    Docker容器的基本操作 所有的docker命令都是以docker开头,也就是指调用docker程序.我学习的第一个命令就是docker run,运行一个容器.以Docker分享02中的容器为例: ...

  9. November 13th, 2017 Week 46th Monday

    Don't undermine your worth by comparing yourself with others. 别拿自己和他人比较,这只会降低你原有的价值. Honestly, I don ...

  10. 51nod 贪心算法题集

    2070 最小罚款: 题意:初始有n元,每个任务有2个参数:t和w,<=t时刻前完成任务才可避免造成损失w.问:如何安排才能尽可能避免损失?一个任务执行时间是一个单位时间. 分析:任务按时间排个 ...