提要
- 下載提示窗口
- 下載方法代碼
下載提示窗口
如圖,界面上有三個主要信息即可,文件名、大小、進度條。下面是詳細的類代碼,使用了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();
}
}
}