简体   繁体   中英

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. 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.

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.
    }
}

Try this in your Changed method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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