引发FileSystemWatcher.Changed事件时程序退出(C#)

Max*_*mer 2 c# filesystemwatcher

所以,我正在尝试将文件更改为通知程序,并且我需要使文件框中的文本更新,只要文件的内容发生更改.这是我到目前为止:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

这似乎正确地引发了事件,但是一旦触及OnChanged事件中的代码,程序退出,没有错误或任何事情,只需关闭.我试图阻止它关闭,我甚至尝试将e.Cancel放在formclosing事件下,但似乎没有任何效果.有任何想法吗?如果需要,我可以提供更多信息.

Jet*_*hro 5

你试过在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.
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常常见的错误,看看这篇文章解决异常.http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t (2认同)