WPF 下载器

提要

  1. 下载提示窗口
  2. 下载方法代码

下载提示窗口

如图,界面上有三个主要信息即可,文件名、大小、进度条。下面是详细的类代码,使用了DataBinding。

下载窗口

DownloadWindow.xaml

<Window x:Class="Demo.Views.DownloadWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Demo.Views"
        mc:Ignorable="d"
        Title="下载" Height="160" Width="300" WindowStyle="ToolWindow" WindowStartupLocation="CenterScreen">
    <DockPanel LastChildFill="False">
        <Label Content="{Binding FileName} DockPanel.Dock="Top" Margin="10"></Label>
        <Label Content="{Binding Size}" DockPanel.Dock="Top" Margin="10,0"></Label>
        <ProgressBar DockPanel.Dock="Bottom" Height="20" Margin="10" Value="{Binding Progress}"></ProgressBar>
    </DockPanel>
</Window>

DownloadWindow.xaml.cs

using System.ComponentModel;
using System.Windows;
namespace Demo.Views
{
    public partial class DownloadWindow : Window, INotifyPropertyChanged
    {
        public DownloadWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; }


        private string size;
        /// <summary>
        /// 大小,1000K / 2000K 的形式
        /// </summary>
        public string Size
        {
            get { return size; }
            set
            {
                size = value;
                OnPropertyChanged("Size");
            }
        }

        private int progress;
        /// <summary>
        /// 进度,数值。进度为100时关闭窗口。
        /// </summary>
        public int Progress
        {
            get { return progress; }
            set
            {
                progress = value;
                OnPropertyChanged("Progress");
                if (value == 100)
                {
                    this.DialogResult = true;
                }
            }
        }

        #region 通知属性 INotifyPropertyChanged实现部分
        public void OnPropertyChanged(string prop)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}

下载方法代码

主要使用System.Net.WebClient类实现的下载、通知、取消下载等操作。

public static void DownloadFile(string httpUrl, string fileName)
{
    var downloadWindow = new DownloadWindow();
    downloadWindow.FileName = fileName;

    using(var webclient=new WebClient())
    {
        //进度通知出去
        webclient.DownloadProgressChanged += (s, e) =>
        {
            downloadWindow.Size = string.Format("{0}K / {1}K", e.BytesReceived / 1024, e.TotalBytesToReceive / 1024);
            downloadWindow.Progress = e.ProgressPercentage;
        };

        //完成信息通知出去,参数为异常信息(正常完成为null)
        webclient.DownloadFileCompleted += (s, e) =>
        {
            if (e.Error == null)
            {
                Console.WriteLine("下载完成。");
            }
            else
            {
                Console.WriteLine(e.Error);
            }
        };

        //确保文件夹存在
        Directory.CreateDirectory( Path.GetDirectoryName(fileName)));

        //开始异步下载
        webclient.DownloadFileAsync(new Uri(httpUrl), fileName);

        //以Dialog方式显示下载框,若用户点击关闭,则取消下载。
        if (downloadWindow.ShowDialog().Value == false)
        {
            Console.WriteLine("取消");
            webclient.CancelAsync();
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,898评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,802评论 18 399
  • 春天你好! 再过两旬,你又要跟我说再见了。请附耳过来,我想对你说说悄悄话。 你知道吗?在所有的季节里,我最喜欢的就...
    二班班阅读 8,366评论 0 0
  • 我根据《刻意练习》这本书总结了自己觉得有用的读书笔记,“刻意练习”是个火爆的概念,书中提到了人们应该如何利用刻意练...
    壁菠盒子阅读 496评论 0 1
  • 清风微徐艳阳天 郁金香彻百花仙 峥嵘岁月重温顾 却留芬芳在人间 郁金香 花语——热情.高雅.能干.聪颖。 ...
    姜冠阅读 232评论 0 2