<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. [基础知识]在PeopleSoft中SMTP设置不生效如何查找问题

    在PeopleSoft中如果配置了工作流邮件或者标准页面的通知,都是可以发送出邮件的,这些邮件都是由SMTP服务器发送.SMTP需要在APP服务器和PRCS服务器中配置. 如果无法从PeopleSof ...

  2. AJAX删除事件与加载数据

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. SoapUI 接口测试之post提交本地数据文件

    SoapUI接口测试之post提交本地数据文件 by:授客 QQ:1033553122 本文主要是针对用SoapUI POST提交本地数据文件的方法做个简单介绍 举例: 文件同步接口 接口地址:htt ...

  4. AsyncTask 处理耗时操作&&显示进度条

    在Android中实现异步任务机制有两种,Handler和AsyncTask.优缺点自己百度,推荐使用AsyncTask. private ProgressDialog dialog; //新建一个对 ...

  5. Unity Profiler CPU Usage(CPU使用情况)

    在Profiler界面点击左侧CPU Usage,Profiler界面下方Hierarchy窗口会列出各个函数对当前CPU的耗时,从大到小排序. 然后分析,各个函数的耗时是否异常,分析有没有可以优化的 ...

  6. 关于form表单提交到Servlet的时候出现tomcat启动错误的解决方法

    1.遇到的问题 今天在写jsp代码的时候通过form表单提交到Servlet的时候出现的tomcat启动错误,琢磨了半天,终于找到了解决方法. 解决问题的关键就在于xml配置的路径和servlet中默 ...

  7. LeetCode题解之Rotate String

    1.题目描述 2.问题分析 直接旋转字符串A,然后做比较即可. 3.代码 bool rotateString(string A, string B) { if( A.size() != B.size( ...

  8. memcached 查看所有的key

    1. cmd上登录memcache   1 > telnet 127.0.0.1 11211 2. 列出所有keys   1 2 3 4 stats items // 这条是命令 STAT it ...

  9. 2. DAS,NAS,SAN在数据库存储上的应用

    一. 硬盘接口类型1. 并行接口还是串行接口(1) 并行接口,指的是并行传输的接口,比如有0~9十个数字,用10条传输线,那么每根线只需要传输一位数字,即可完成.从理论上看,并行传输效率很高,但是由于 ...

  10. SQL Server 2016 中有外键的表无法被Truncate,只能被Delete

    问: I get the following message even when the table that references it is empty: "Cannot truncat ...