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

时间:2011-08-02 15:45:22

标签: 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);
    }

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

2 个答案:

答案 0 :(得分: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.
    }
}

答案 1 :(得分:3)

在Changed方法中尝试此操作

if (TB.InvokeRequired)
{
   TB.Invoke(new MethodInvoker(delegate { TB.Text = File.ReadAllText(path); }));
}