如何使用TXT文件不断更新RichTextBox?

时间:2015-11-26 03:30:18

标签: c# richtextbox filesystemwatcher

我有这段代码,应该使用 usedPath 的内容随时更新 richTextBox2 ,但事实并非如此。

 private void watch()
    {
        var usedPath = Path.Combine(Directory.GetCurrentDirectory(), "usedwords.txt");

        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = usedPath;
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.txt*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        string usedPath = Path.Combine(Directory.GetCurrentDirectory(), "usedwords.txt");
        richTextBox2.LoadFile(usedPath, RichTextBoxStreamType.PlainText);
    }

有人可以帮我弄明白我的错吗?

1 个答案:

答案 0 :(得分:0)

问题1:您的watcher.Path =单个文件的路径,这将导致错误。

解决方案:请看:Use FileSystemWatcher on a single file in C#

watcher.Path = Path.GetDirectoryName(filePath1); 
watcher.Filter = Path.GetFileName(filePath1);

问题2:访问richTextBox2中的OnChanged()会导致跨线程错误

解决方案:使用此:

private void OnChanged(object source, FileSystemEventArgs e)
{
    Invoke((MethodInvoker)delegate
    {
          string usedPath = Path.Combine(Directory.GetCurrentDirectory(), "usedwords.txt");
          richTextBox2.LoadFile(usedPath, RichTextBoxStreamType.PlainText);      
    });
}

问题3:尝试加载文件时可能会出错,而其他一些程序正在写入文件。

(可能)解决方案:在Thread.Sleep(10)

中尝试LoadFile之前加OnChanged
    private void OnChanged(object source, FileSystemEventArgs e)
    {
        Thread.Sleep(10);
        Invoke((MethodInvoker)delegate
        {
            richTextBox1.LoadFile(usedPath, RichTextBoxStreamType.PlainText);
        });
    }

我的完整代码:

public partial class Form1 : Form
{
    string usedPath = @"C:\Users\xxx\Desktop\usedwords.txt";

    public Form1()
    {
        InitializeComponent();
        watch();
    }

    private void watch()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName(usedPath);
        watcher.Filter = Path.GetFileName(usedPath);
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        Thread.Sleep(10);
        Invoke((MethodInvoker)delegate
        {
            richTextBox1.LoadFile(usedPath, RichTextBoxStreamType.PlainText);
        });
    }
}