简体   繁体   English

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

[英]Program exits when FileSystemWatcher.Changed event is raised (C#)

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. 这似乎正确地引发了事件,但是一旦触及OnChanged事件中的代码,程序退出,没有错误或任何事情,只需关闭。 I have tried to stop it from closing, I have even tried putting e.Cancel under the formclosing event, but nothing seems to work. 我试图阻止它关闭,我甚至尝试将e.Cancel放在formclosing事件下,但似乎没有任何效果。 Any ideas? 有任何想法吗? I can provide more info if needed. 如果需要,我可以提供更多信息。

Have you tried wrapping the code in try catch 你试过在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.
    }
}

Try this in your Changed method 在Changed方法中尝试此操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM