c# - 在运行时从 txt 文件更新文本框而不单击 "refresh"

标签 c# wpf xaml

在 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/

相关文章:

c# - 我收到 System.NullReferenceException : Object reference not set to an instance of an object when trying to add a value to an array at runtime

c# - 检查玩家是否通过了两个门

.net - 如何在 WPF 应用程序中实现气球消息

c# - 标记扩展 'StaticResourceExtension' 需要在 IServiceProvider 中为 ProvideValue 实现 'IXamlSchemaContextProvider'

c# - 查询主体必须以 select 子句或 group 子句结尾为什么这里会出错?

c# - Entity Framework : The context is being used in Code First mode with code that was generated from an EDMX file

wpf - 使用元素语法设置 UserControl 上的附加属性值

api - 如何使用 Xamarin 在单元格 View 中显示数据

c# - LinearGradiantBrush 单独应用于下划线和文本,但不一起应用于

c# - 标识符必须声明为 ORA-06550 和 PLS-00201