在日常工作和生活中,我们经常需要处理大量的文件,例如整理文档、备份数据等。手动逐一查找和复制文件不仅耗时费力,而且容易出错。本项目旨在利用WPF开发一个用户友好的批量文件处理工具,用户可以通过简单的界面输入源目录、目标目录及文件过滤条件,程序将自动完成文件的查找与复制操作,并提供操作日志以供用户查看。
二、项目目标
FileBatchCopy
),选择保存位置,点击“创建”。在MainWindow.xaml
中设计如下界面元素:
.txt
)。示例代码 (MainWindow.xaml
):
xml复制<Window x:Class="FileBatchCopy.MainWindow"
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"
mc:Ignorable="d"
Title="批量文件查找复制工具" Height="500" Width="700">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 源目录 -->
<StackPanel Orientation="Horizontal" Grid.Row="0">
<Label Content="源目录:" Width="60"/>
<TextBox x:Name="txtSourceDir" Width="400"/>
<Button Content="浏览" Click="BrowseSourceDir_Click" Margin="10,0,0,0"/>
</StackPanel>
<!-- 文件扩展名 -->
<StackPanel Orientation="Horizontal" Grid.Row="1">
<Label Content="文件扩展名:" Width="80"/>
<TextBox x:Name="txtFileExt" Width="200"/>
<TextBlock Text=".扩展名(如txt)" Foreground="Gray" VerticalAlignment="Center"/>
</StackPanel>
<!-- 目标目录 -->
<StackPanel Orientation="Horizontal" Grid.Row="2">
<Label Content="目标目录:" Width="60"/>
<TextBox x:Name="txtTargetDir" Width="400"/>
<Button Content="浏览" Click="BrowseTargetDir_Click" Margin="10,0,0,0"/>
</StackPanel>
<!-- 日志显示 -->
<TextBox x:Name="txtLog" Grid.Row="3" Height="150" IsReadOnly="True" VerticalScrollBarVisibility="Auto" Margin="0,10,0,0"/>
<!-- 开始按钮 -->
<Button Content="开始复制" Width="100" HorizontalAlignment="Right" Margin="0,10,10,0" Grid.Row="4" Click="StartCopy_Click"/>
</Grid>
</Window>
在MainWindow.xaml.cs
中实现各个按钮的事件处理逻辑,包括浏览目录、查找文件、复制文件以及记录日志。
示例代码 (MainWindow.xaml.cs
):
csharp复制using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
namespace FileBatchCopy
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// 浏览源目录
private void BrowseSourceDir_Click(object sender, RoutedEventArgs e)
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
dialog.Description = "请选择源目录";
dialog.ShowNewFolderButton = false;
var result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
txtSourceDir.Text = dialog.SelectedPath;
}
}
}
// 浏览目标目录
private void BrowseTargetDir_Click(object sender, RoutedEventArgs e)
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
dialog.Description = "请选择目标目录";
dialog.ShowNewFolderButton = true;
var result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
txtTargetDir.Text = dialog.SelectedPath;
}
}
}
// 开始复制
private async void StartCopy_Click(object sender, RoutedEventArgs e)
{
string sourceDir = txtSourceDir.Text.Trim();
string targetDir = txtTargetDir.Text.Trim();
string fileExt = txtFileExt.Text.Trim();
if (string.IsNullOrEmpty(sourceDir))
{
MessageBox.Show("请先选择源目录!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (string.IsNullOrEmpty(targetDir))
{
MessageBox.Show("请先选择目标目录!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (string.IsNullOrEmpty(fileExt) || !fileExt.StartsWith("."))
{
MessageBox.Show("请输入有效的文件扩展名(如 .txt)!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
txtLog.Clear();
btnStartCopy.IsEnabled = false;
progressBar.Visibility = Visibility.Visible;
try
{
var files = Directory.GetFiles(sourceDir, $"*{fileExt}", SearchOption.AllDirectories);
int total = files.Length;
int copied = 0;
foreach (var file in files)
{
try
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(targetDir, fileName);
// 如果目标文件已存在,可以选择跳过或覆盖
if (File.Exists(destFile))
{
// 这里选择跳过
Log($"文件已存在,跳过: {fileName}");
continue;
}
// 创建目标文件夹(如果不存在)
string destFolder = Path.GetDirectoryName(destFile);
Directory.CreateDirectory(destFolder);
// 复制文件
File.Copy(file, destFile, overwrite: false);
Log($"已复制: {fileName}");
copied++;
}
catch (Exception ex)
{
Log($"复制失败: {Path.GetFileName(file)} - {ex.Message}");
}
// 更新进度
double progress = (double)copied / total * 100;
progressBar.Value = progress;
await Task.Delay(10); // 界面响应更流畅
}
Log($"操作完成!共复制了 {copied} 个文件。");
}
catch (Exception ex)
{
Log($"发生错误: {ex.Message}");
}
finally
{
btnStartCopy.IsEnabled = true;
progressBar.Visibility = Visibility.Collapsed;
}
}
// 记录日志
private void Log(string message)
{
Dispatcher.Invoke(() =>
{
txtLog.AppendText($"{DateTime.Now}: {message}\n");
});
}
}
}
注意事项:
async
和await
)来保持界面的响应性。上述示例中使用了Task.Delay
模拟异步操作,实际项目中可以使用Task.Run
来执行耗时的文件操作。通过以上步骤,我们成功地使用WPF开发了一个批量文件查找复制工具。该项目不仅实现了基本的文件查找和复制功能,还注重用户体验和程序的健壮性。以下是项目过程中的一些关键点和收获:
async
和await
进行异步编程的方法,提高了应用的响应性。未来,可以在此基础上进一步扩展功能,如增加文件压缩、加密、搜索过滤等高级功能,以满足更多用户的需求。同时,也可以探索使用MVVM模式重构代码,提升代码的可维护性和可扩展性。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有