WPF实现运行时自动同步Txt文件更新至TextBox(无需手动刷新)
实现WPF TextBox自动同步本地Txt文件变更
当然可以实现自动同步!WPF里我们可以用.NET自带的FileSystemWatcher类来监控目标Txt文件的变化,一旦文件被修改,就自动触发TextBox的更新,完全不用手动点击刷新按钮。下面是具体的实现示例:
后台C#代码实现
首先我们需要调整原有的代码,加入FileSystemWatcher的监控逻辑,同时优化文本读取的逻辑(避免重复追加内容):
using System.IO; using System.Windows; public partial class MyWindow : Window { private FileSystemWatcher _fileWatcher; private string _targetFilePath = @"D:\Log.txt"; public MyWindow() { InitializeComponent(); // 初始化文件监控器 SetupFileWatcher(); // 首次加载文件内容 ReadFromTxt(); } private void SetupFileWatcher() { _fileWatcher = new FileSystemWatcher { // 设置监控的目录(注意是文件所在的文件夹,不是文件本身) Path = Path.GetDirectoryName(_targetFilePath), // 设置要监控的文件名 Filter = Path.GetFileName(_targetFilePath), // 启用文件修改、文件名变更的通知 NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName, // 开启事件触发 EnableRaisingEvents = true }; // 绑定文件修改事件 _fileWatcher.Changed += OnFileChanged; // 绑定文件重命名事件,防止文件改名后丢失监控 _fileWatcher.Renamed += OnFileRenamed; } private void OnFileChanged(object sender, FileSystemEventArgs e) { // 注意:FileSystemWatcher的事件在非UI线程触发,必须切换到UI线程更新控件 Dispatcher.Invoke(() => { ReadFromTxt(); }); } private void OnFileRenamed(object sender, RenamedEventArgs e) { // 更新监控的文件名和路径 _fileWatcher.Filter = e.Name; _targetFilePath = e.FullPath; Dispatcher.Invoke(() => { ReadFromTxt(); }); } private void ReadFromTxt() { try { // 先清空TextBox,避免重复加载内容 MyTextBox.Clear(); string[] lines = File.ReadAllLines(_targetFilePath); foreach (string line in lines) { MyTextBox.AppendText(line + Environment.NewLine); } // 自动滚动到最新内容 MyTextBox.ScrollToEnd(); } catch (IOException ex) { // 处理文件被其他进程占用等异常 MessageBox.Show($"读取文件失败:{ex.Message}"); } } // 保留原有的手动刷新按钮逻辑(可选) private void Refresh(object sender, RoutedEventArgs e) { ReadFromTxt(); } protected override void OnClosed(EventArgs e) { // 窗口关闭时释放监控器资源,避免内存泄漏 _fileWatcher?.Dispose(); base.OnClosed(e); } }
关键说明
- FileSystemWatcher核心配置:我们监控文件所在的目录,指定目标文件名,并开启
Changed和Renamed事件通知,确保文件修改或改名时都能触发更新。 - UI线程安全:因为
FileSystemWatcher的事件回调是在后台线程执行的,直接操作UI控件会引发线程异常,所以必须用Dispatcher.Invoke切换到UI线程更新TextBox。 - 异常处理:添加了
try-catch块处理文件被其他进程占用的情况,避免程序崩溃。 - 资源释放:窗口关闭时手动释放
FileSystemWatcher的资源,防止内存泄漏。
XAML部分(无需额外修改)
你的原有XAML可以保持不变,比如包含TextBox和Refresh按钮的布局:
<Window x:Class="YourNamespace.MyWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Log Viewer" Height="450" Width="800"> <Grid> <TextBox x:Name="MyTextBox" Margin="10" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" /> <Button Content="Refresh" Margin="10" VerticalAlignment="Bottom" HorizontalAlignment="Right" Click="Refresh"/> </Grid> </Window>
这样你的TextBox就会自动同步D:\Log.txt的所有变更,不需要手动点击刷新按钮啦!
内容的提问来源于stack exchange,提问作者Flufy
相关产品推荐
相关产品推荐

