zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
    

      

  • 相关阅读:
    vivado操作基本问题
    IIC通信控制的AD5259------在调试过程中遇到的奇葩问题
    FPGA基础架构总结
    PLL到底是个啥么东西呢?
    CSS-3 Transform 的使用
    CSS-3 box-shadow 的使用
    一些CSS3的乐趣
    CSS-3 文字阴影—text-shadow 的使用
    Jquery 较好的效果
    如何关闭输入法
  • 原文地址:https://www.cnblogs.com/wgscd/p/9469616.html
Copyright © 2011-2022 走看看