提要
- 下载提示窗口
- 下载方法代码
下载提示窗口
如图,界面上有三个主要信息即可,文件名、大小、进度条。下面是详细的类代码,使用了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();
}
}
}