2

So, I'm trying to make a file changed notifier, and I need to make it so the text in a textbox updates whenever the contents of the file are changed. This is what I have so far:

    string path = "C:/Users/Max/Dropbox/Public/IM.txt";
    StringBuilder b = new StringBuilder();
    private void Window_Loaded(object sender, EventArgs e)
    {
        TB.Text = File.ReadAllText(path);
        b.Append(TB.Text);
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = path.Remove(path.Length - 6, 6);
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.txt";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
        TB.SelectionStart = TB.Text.Length;
        TB.ScrollToCaret();
    }
    private void OnChanged(object source, FileSystemEventArgs e)
    {
        TB.Text = File.ReadAllText(path);
    }

This seems to raise the event correctly, but as soon as it touches the code in the OnChanged event, the program exits, no errors or anything, just closes. I have tried to stop it from closing, I have even tried putting e.Cancel under the formclosing event, but nothing seems to work. Any ideas? I can provide more info if needed.

Max Weimer
  • 21
  • 2

2 Answers2

5

Have you tried wrapping the code in try catch

private void OnChanged(object source, FileSystemEventArgs e)
{
    try
    {
        TB.Text = File.ReadAllText(path);
    }catch(Exception e)
    {
        //Show exception in messagebox or log to file.
    }
}
Jethro
  • 5,896
  • 3
  • 23
  • 24
  • 1
    or even just put `System.Diagnostics.Debugger.Break();` in the catch block – kͩeͣmͮpͥ ͩ Aug 02 '11 at 15:51
  • I get the error "Cross-thread operation not valid: Control 'TB' accessed from a thread other than the thread it was created on." two times – Max Weimer Aug 02 '11 at 15:54
  • 2
    Very commont error, take a look at this post for solution to the exception. http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t – Jethro Aug 02 '11 at 15:55
  • Thank you, that thread had just the answer i was looking for. – Max Weimer Aug 02 '11 at 16:07
3

Try this in your Changed method

if (TB.InvokeRequired)
{
   TB.Invoke(new MethodInvoker(delegate { TB.Text = File.ReadAllText(path); }));
}
Asdfg
  • 11,362
  • 24
  • 98
  • 175