2015-11-26 46 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