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 ...
随机推荐
- Android:Error:Execution failed for task ':app:clean'. > Unable to delete directory
as clean项目之后有时候会报错. 可以找得到目录删掉,然后重启as,但是下次clean可能又会报类似的错误. 解决方法如下: 进入File-Setting-Build,Execution,De ...
- 大数据【二】HDFS部署及文件读写(包含eclipse hadoop配置)
一 原理阐述 1' DFS 分布式文件系统(即DFS,Distributed File System),指文件系统管理的物理存储资源不一定直接连接在本地节点上,而是通过计算机网络与节点相连.该系统架构 ...
- 【Redis】Redis学习(七) Redis 持久化之RDB和AOF
Redis 持久化提供了多种不同级别的持久化方式:一种是RDB,另一种是AOF. RDB 持久化可以在指定的时间间隔内生成数据集的时间点快照(point-in-time snapshot). AOF ...
- java io详解(1)
一.java io结构图 二.java io的开始:文件 三.字节流: 一.java io结构图 流分类: 1.Java的字节流 InputStream是所有字节输入流的祖先,而OutputSt ...
- 反射式DLL注入--方法
使用RWX权限打开目标进程,并为该DLL分配足够大的内存. 将DLL复制到分配的内存空间. 计算DLL中用于执行反射加载的导出的内存偏移量. 调用CreateRemoteThread(或类似的未公开的 ...
- Sql Server与.Net(C#)中星期值对比
最近发现Sql Server与.Net(C#)中星期值居然不匹配,倒不知道依哪一个了. 1.Sql Server declare @date datetime; set @date = '2017-0 ...
- C# 引用的程序集没有强名称
首先查一下什么是强名称程序集,见百度百科帖子:http://baike.baidu.com/view/1145682.htm简单来说,就是为了解决Windows Dll Hell问题的,即不同公司开发 ...
- Python socket应用
Server端: #-*- coding: UTF-8 -*- import socket,time host='192.168.0.9' port=12307 s=socket.socket(soc ...
- Linux运维之--LVS、Nginx、HAproxy有什么区别?
LVS: 是基于四层的转发 HAproxy: 是基于四层和七层的转发,是专业的代理服务器 Nginx: 是WEB服务器,缓存服务器,又是反向代理服务器,可以做七层的转发 区别: LVS由于是基于四层的 ...
- MySQL基础之---mysqlimport工具和LOAD DATA命令导入文本文件
1.mysqlimport工具的使用 看一下命令的使用方法: shell > mysqlimport -u root -p [--LOCAL] DBname File [option] --f ...