uwp 下载文件显示进度并解压文件。

<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="909" Height="429">
<Grid > <Grid Name="gridPercent" VerticalAlignment="Top" Height="57" Margin="183,0,0,0">
<Rectangle Name="lbPercent" VerticalAlignment="Top" Height="53" Margin="0" HorizontalAlignment="Left" Width="0" Fill="Blue"/>
</Grid>
<TextBlock Name="txt" Foreground="Red" Text="0%" VerticalAlignment="Top" Height="53" Margin="200,0,7,0" HorizontalAlignment="Stretch"/> <Button x:Name="btnDownload" Background="WhiteSmoke" HorizontalAlignment="Left" Height="57" VerticalAlignment="Top" Width="178" Content="download" Click="BtnDownload_Click" /> </Grid>
</Page>

  

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI;
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.Media.Imaging;
using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace App4
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded; }
private bool isDownloading = false; private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{ } private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
dowloadFile();
} 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";
bool isDownloadComplete = false;
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;
string localFile = "test.zip";
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();
isDownloadComplete = true;
this.Invoke(new Action(() =>
{
txt.Text = "100%";//显示下载百分比
txt.UpdateLayout();
}));
await new MessageDialog("download complete!").ShowAsync();
UnzipFile(localFile);
}
} }
catch (Exception ex)
{
await new MessageDialog("download error:" + ex.ToString()).ShowAsync();
}
isDownloading = false;
} 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(); }); } private async void UnzipFile(string zipFileName)
{ Random rnd = new Random(); string existfile = "Elasticsearch.pptx";
var localFolder = ApplicationData.Current.LocalFolder; //路径形如:C:\Users\gwang\AppData\Local\Packages\347b02f6-8bb6-4c2c-a494-82f3fb42f42a_px2gx6zt1mshw\LocalState //尝试删除旧文件
var oldFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(existfile);
if (oldFile != null)
{
var file = await localFolder.GetFileAsync(existfile);
await file.DeleteAsync();
}
//开始解压
var archive = await localFolder.GetFileAsync(zipFileName);//eg test.zip
ZipFile.ExtractToDirectory(archive.Path, localFolder.Path + "\\" + rnd.Next(1, 20000));//如果目标文件存在会异常
await new MessageDialog("unzip done!").ShowAsync(); } /// <summary>
/// another sample, not know how to show download processs
/// </summary>
async void downloadFileUseHttpClient()
{ string serverUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";
System.Net.Http.HttpClientHandler hand = new System.Net.Http.HttpClientHandler();
// System.Net.Http.MessageProcessingHandler processMessageHander = new System.Net.Http.MessageProcessingHandler();
System.Net.Http.HttpClient localHttpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpRequestMessage httpRequestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, serverUrl);
var resp = await localHttpClient.SendAsync(httpRequestMessage);
Stream stream = await resp.Content.ReadAsStreamAsync();
//............ } }
}

  

另外一种方法是利用:System.Net.Http.HttpClient

  /// <summary>
/// another sampe
/// </summary>
async void downloadFileUseHttpClient()
{ string serverUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";
System.Net.Http.HttpClient localHttpClient = new System.Net.Http.HttpClient();
var progress = new Progress<HttpDownloadProgress>(percent => {
txt.Text =""+ percent.BytesReceived+"/"+percent.TotalBytesToReceive;
txt.UpdateLayout();
}); CancellationToken token=new CancellationToken();
var data= await HttpClientExtensions.GetByteArrayAsync(localHttpClient, new Uri(serverUrl), progress, token);
var folder = ApplicationData.Current.LocalFolder;
string localFile = "test.zip";
StorageFile file = await folder.CreateFileAsync(localFile, CreationCollisionOption.ReplaceExisting);
using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
dataWriter.WriteBytes(data.ToArray());
transaction.Stream.Size = await dataWriter.StoreAsync();
await dataWriter.FlushAsync();
await transaction.CommitAsync();
} } } public static class HttpClientExtensions
{
private const int BufferSize = 8192; public static async Task<byte[]> GetByteArrayAsync(this HttpClient client, Uri requestUri, IProgress<HttpDownloadProgress> progress, CancellationToken cancellationToken)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
} using (var responseMessage = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
{
responseMessage.EnsureSuccessStatusCode(); var content = responseMessage.Content;
if (content == null)
{
return Array.Empty<byte>();
} var headers = content.Headers;
var contentLength = headers.ContentLength;
using (var responseStream = await content.ReadAsStreamAsync().ConfigureAwait(false))
{
var buffer = new byte[BufferSize];
int bytesRead;
var bytes = new List<byte>(); var downloadProgress = new HttpDownloadProgress();
if (contentLength.HasValue)
{
downloadProgress.TotalBytesToReceive = (ulong)contentLength.Value;
}
progress?.Report(downloadProgress); while ((bytesRead = await responseStream.ReadAsync(buffer, 0, BufferSize, cancellationToken).ConfigureAwait(false)) > 0)
{
bytes.AddRange(buffer.Take(bytesRead)); downloadProgress.BytesReceived += (ulong)bytesRead;
progress?.Report(downloadProgress);
} return bytes.ToArray();
}
}
} public struct HttpDownloadProgress
{
public ulong BytesReceived { get; set; } public ulong? TotalBytesToReceive { get; set; }
}

  

uwp 下载文件显示进度并解压文件的更多相关文章

  1. axios下载文件乱码问题 无法解压 文件损坏

    /* 下载附件 */ downloadFile(fileName) { // window.open(url); var that = this; var url = "PO2116&quo ...

  2. Linux命令(16)压缩,解压文件

    tar: 简介:tar命令只是把目录打包成一个归档(文件),并不负责压缩.在tar命令中可以带参数调用gzip或bzip2压缩.因为gzip和bzip2只能压缩单个文件. 在linux下是不需要后缀名 ...

  3. HDFS中文件的压缩与解压

    HDFS中文件的压缩与解压 文件的压缩有两大好处:1.可以减少存储文件所需要的磁盘空间:2.可以加速数据在网络和磁盘上的传输.尤其是在处理大数据时,这两大好处是相当重要的. 下面是一个使用gzip工具 ...

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

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

  5. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  6. AIX系统上压缩与解压文件

    压缩. 命令格式: #tar -cvf (或xvf)+文件名+设备 C:是本地到其他设备 x:是其他设备到本地 r:是追加,比如打包时,将其他文件追加进来使用该参数. t:显示tar包里的内容,但还原 ...

  7. linux下tar gz bz2 tgz z等众多压缩文件的压缩与解压方法

    Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通常都是以.tar结尾的.生成tar包后,就可以用其它的程序来进 行压缩了,所以首先就来讲讲ta ...

  8. (转)使用 linux tar 命令压缩与解压文件

    原文链接 http://www.cnblogs.com/qq78292959/archive/2011/07/06/2099427.html tar -c: 建立压缩档案-x:解压-t:查看内容-r: ...

  9. java 压缩以及解压文件,有tar,zip,gz(gizp)和解压

    package com.yabsz.decompCompr; import java.io.File; import java.util.ArrayList; import java.util.Lis ...

  10. Linux学习笔记之AIX系统上压缩与解压文件

    0x00 概述 AIX机器真难用,一时半会还真适应不了.   0x01 压缩tar 命令格式: # tar -cvf (或xvf)+文件名+设备 C:是本地到其他设备 x:是其他设备到本地 r:是追加 ...

随机推荐

  1. P9119 [春季测试 2023] 圣诞树

    参考博客: 春季测试 2023] 圣诞树 题解 - 洛谷专栏 (luogu.com.cn) 题意:给定二维平面上一个凸多边形的 \(n\) 个顶点, 求一种方案,使得从最高点开始,不重复地经过所有点后 ...

  2. Python中序列化/反序列化JSON格式的数据

    基本概念 JSON: JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式.简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言. 易于 ...

  3. HAL+CubeIDE,STM32F407ZGT6正点原子探索者,舵机驱动,从零开始

    CubeIDE_HAL库_从零开始玩舵机 1.材料准备 开发板:正点原子STM32F407ZGT6探索者 舵机:SG90 舵机线材分辨:褐色 / 红色 / 橘黄色 -- GND / VCC / PWM ...

  4. 【Azure App Service】在App Service for Windows上验证能占用的内存最大值

    问题描述 在创建App Service服务的时候,根据定价层不同,内存使用的最大值也有不同.但在实际测试中,发现内存最大只能占用2GB左右, 而定价层中内存分配明明是大于2GB(比如B3定价层的内存为 ...

  5. 探索 USB 上网模组,Air780ER 当仁不让

    今天探索的是USB上网模组,我推荐的是Air780ER模组,本文从用户实际使用的角度,解答大家对Air780ER最关心的一些问题,内容不深入探究技术细节,更多从选型.应用等非技术维度展开. 一.Air ...

  6. webpack中引用jQuery的四种方式

    import webpack中是根据一个入口文件开始收集依赖. import $ from 'jquery' 但是一个项目中通常有很多个地方都用到了jQuery,每个模块都要这样的一行代码 那么如何解 ...

  7. Http状态码502常见原因及排错思路

    Http状态码502常见原因及排错思路 502表示Bad Gateway.当Nginx返回502错误时,通常表示Nginx作为代理服务器无法从上游服务器(如:我们的后端服务器地址)获取有效的响应.导致 ...

  8. Java 并发编程实战学习笔记——CountDownLatch的使用

    public class CountDownLatch extends Object 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 用给定的计数 初始化 Co ...

  9. Java多线程设计模式(6)两阶段终止模式

    一 Two-Phase Termination Pattern Two-Phase Termination Pattern,指的就是当希望结束一个线程的时候,送出一个终止请求,但是不会马上停止,做一些 ...

  10. 使用SwingWorker异步加载JTree

    SwingWorker是Java SE 6.0新加入的一个工具包,利用它可以使长时间运行并更新用户界面的任务大大简化.本文以一个异步加载JTree的demo演示了SwingWorker的基本功能. 环 ...