在 wpf 中,我有一个文本框,它的内容来自一个 txt 文件。
在后面的代码中它看起来像:
public MyWindow()
{
InitializeComponent();
ReadFromTxt();
}
void Refresh(object sender, RoutedEventArgs e)
{
ReadFromTxt();
}
void ReadFromTxt()
{
string[] lines = System.IO.File.ReadAllLines(@"D:\Log.txt");
foreach (string line in lines)
{
MyTextBox.AppendText(line + Environment.NewLine);
}
}
问题是 txt 文件内容在运行时会发生变化,是否可以与这些变化同步?我的意思是,如果更改 txt 文件,文本框内容也会更改。如果可能,请提供一些代码示例我 c# 或 XAML。
我现在的解决方案是我做了一个“刷新”按钮,它再次从 txt 文件中读取
最佳答案
您可以配置FileSystemWatcher
。我添加了 FileWatcherConfigure
函数作为示例。
每当文件发生变化时,FileChanged
事件将被发布。您应该使用该事件触发 RefreshTextbox
方法。
FileSystemWatcher fileWatcher = new FileSystemWatcher();
string filePath = @"./Log.txt";
public MainWindow()
{
InitializeComponent();
ReadFromTxt();
FileWatherConfigure();
}
public void FileWatherConfigure()
{
fileWatcher.Path = System.IO.Path.GetDirectoryName(filePath);
fileWatcher.Filter = System.IO.Path.GetFileName(filePath);
fileWatcher.Changed += FileWatcher_Changed;
fileWatcher.EnableRaisingEvents = true;
}
private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
ReadFromTxt();
}
void ReadFromTxt()
{
string[] lines = System.IO.File.ReadAllLines(filePath);
MyTextBox.Dispatcher.Invoke(() => { this.MyTextBox.Text = string.Join(Environment.NewLine, lines); });
}
关于c# - 在运行时从 txt 文件更新文本框而不单击 "refresh",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417280/