在WPF中复制文件时,如何调用线程,显示进度条。
<Window x:Class="WpfThreadTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Closed="Window_Closed" Loaded="Window_Loaded" Height="209" Width="537" ResizeMode="NoResize"> <Grid Height="186"> <Grid.ColumnDefinitions> <ColumnDefinition Width="132*" /> <ColumnDefinition Width="236*" /> <ColumnDefinition Width="147*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Name="textBlock1" Text="当前时间" Margin="35 10" Height="auto" Width="auto" /> <TextBox Grid.Column="1" Name="displayTimeByThread" Height="auto" Margin="0 10" /> <TextBlock Grid.Row="1" Name="textBlock2" Margin="35 10 0 10 " Text="源文件位置" /> <TextBox Grid.Column="1" Grid.Row="1" Name="srcFile" Margin="0 10" /> <TextBox Grid.Column="1" Grid.Row="2" Name="saveFilePath" Margin="0 10" /> <TextBlock Grid.Row="2" Name="textBlock3" Text="目标文件位置" Margin="35 10 0 10" /> <Button Content="..." Grid.Column="2" Grid.Row="1" Name="button1" Margin="10,10,66,10" Click="button1_Click" /> <Button Content="..." Grid.Column="2" Grid.Row="2" Name="button2" Margin="10,10,66,10" Height="23" Click="button2_Click"/> <Button Content="开始时间线程" Grid.Column="2" Name="button3" Margin="10,10,35,10" Height="23" Click="button3_Click" /> <Button Content="开始文件Copy线程" Grid.Column="2" Grid.Row="3" Height="29" HorizontalAlignment="Left" Name="button4" VerticalAlignment="Top" Width="119" Click="button4_Click" /> <TextBlock Grid.Row="3" Name="copyFlag" Text="开始复制" /> <TextBlock Name="displayCopyInfo" Text="文件Copy进行中" Grid.Row="3" Grid.Column="1" /> <ProgressBar Grid.Column="1" Grid.Row="4" Margin="0 2" Height="8" Name="copyProgress" /> </Grid> </Window>
namespace WpfThreadTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
Thread timeThread;
Thread copyThread;
public MainWindow()
{
InitializeComponent();
this.displayTimeByThread.Text = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日 hh:mm:ss"); ;
timeThread = new Thread(new ThreadStart(DispatcherThread));
}
private void button3_Click(object sender, RoutedEventArgs e)
{
timeThread.Start();
}
public void DispatcherThread()
{
//可以通过循环条件来控制UI的更新
while (true)
{
///线程优先级,最长超时时间,方法委托(无参方法)
displayTimeByThread.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new Action(UpdateTime));
Thread.Sleep(1000);
}
}
private void UpdateTime()
{
this.displayTimeByThread.Text = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日 hh:mm:ss");
}
private void Window_Closed(object sender, EventArgs e)
{
///关闭所有启动的线程
timeThread.Abort();
copyThread.Abort();
Application.Current.Shutdown();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
///设定要复制的文件全路径
OpenFileDialog openFile = new OpenFileDialog();
openFile.AddExtension = true;
openFile.CheckPathExists = true;
openFile.Filter = "*.rar|*.rar|all files|*.*";
openFile.FilterIndex = 0;
openFile.Multiselect = false;
bool? f=openFile.ShowDialog();
if (f!=null && f.Value)
{
this.srcFile.Text = openFile.FileName;
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
///设定目标文件全路径
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.AddExtension = true;
saveFile.Filter = "*.rar|*.rar|all files|*.*";
saveFile.FilterIndex = 0;
bool? f= saveFile.ShowDialog();
if (f != null && f.Value)
{
this.saveFilePath.Text = saveFile.FileName;
}
}
private void button4_Click(object sender, RoutedEventArgs e)
{
string fileName=this.srcFile.Text.Trim();
string destPath=this.saveFilePath.Text.Trim();
if(!File.Exists(fileName))
{
MessageBox.Show("源文件不存在");
return;
}
///copy file and nodify ui that rate of progress of file copy
this.copyFlag.Text = "开始复制。。。";
//设置进度条最大值,这句代码写的有点郁闷
this.copyProgress.Maximum = (new FileInfo(fileName)).Length;
//保存复制文件信息,以进行传递
CopyFileInfo c = new CopyFileInfo() { SourcePath = fileName, DestPath = destPath };
//线程异步调用复制文件
copyThread = new Thread(new ParameterizedThreadStart(CopyFile));
copyThread.Start(c);
this.copyFlag.Text = "复制完成。。。";
}
/// <summary>
/// 复制文件的委托方法
/// </summary>
/// <param name="obj">复制文件的信息</param>
private void CopyFile(object obj)
{
CopyFileInfo c = obj as CopyFileInfo;
CopyFile(c.SourcePath, c.DestPath);
}
/// <summary>
/// 复制文件
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="destPath"></param>
private void CopyFile( string sourcePath,string destPath)
{
FileInfo f = new FileInfo(sourcePath);
FileStream fsR = f.OpenRead();
FileStream fsW = File.Create(destPath);
long fileLength = f.Length;
byte[] buffer = new byte[1024];
int n = 0;
while (true)
{
///设定线程优先级
///异步调用UpdateCopyProgress方法
///并传递2个long类型参数fileLength 与 fsR.Position
this.displayCopyInfo.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle,
new Action<long, long>(UpdateCopyProgress), fileLength, fsR.Position);
//读写文件
n=fsR.Read(buffer, 0, 1024);
if (n==0)
{
break;
}
fsW.Write(buffer, 0, n);
fsW.Flush();
Thread.Sleep(1);
}
fsR.Close();
fsW.Close();
}
private void UpdateCopyProgress(long fileLength,long currentLength)
{
this.displayCopyInfo.Text = string.Format("总大小:{0},已复制:{1}", fileLength, currentLength);
//刷新进度条
this.copyProgress.Value = currentLength;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
public class CopyFileInfo
{
public string SourcePath { get; set; }
public string DestPath { get; set; }
}
}
这篇文档对您是否有帮助?