2015-11-26 20 views
1

我有这个代码,它应该保持richTextBox2随时更新usedPath的内容,但它没有。如何使用TXT文件不断更新RichTextBox?

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); 
    } 

有人能帮我弄清楚我有什么问题吗?

回答

0

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

解决方法:看看这个:Use FileSystemWatcher on a single file in C#

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

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

解决方案:使用此:

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

问题3:尝试使用LoadFile而其他程序正在写入时可能会出现错误。

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

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

试图LoadFile之前我的完整代码:

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); 
     }); 
    } 
} 
+0

我让你讲了修改,虽然仍然不工作不幸。 – Asubaba

+0

我刚刚添加了第三个可能的问题。我可以知道你有什么错误吗? – interceptwind

+0

我不相信我会收到任何错误。 – Asubaba