Search code examples
c#event-handlingfilesystemwatcher

C# FileSystemWatcher Events Not Firing


I'm trying to implement a FileSystemWatcher. However, my OnChange event handler is never getting called. The watcher is supposed to be monitoring a log file that is being updated by another thread in the process. The file is opened using new StreamWriter(File.Open("C:\\temp\\myLog.txt", FileMode.Create, FileAccess.Write, FileShare.Read)); Any ideas?

public MyFormConstructor()
{
    InitializeComponent();

    this._fileSystemWatcher = new FileSystemWatcher();
    this._fileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;
    this._fileSystemWatcher.Path = "C:\\temp\\";
    this._fileSystemWatcher.Filter = "myLog.txt";
    this._fileSystemWatcher.Changed += this.OnLogChanged;
    this._fileSystemWatcher.Created += this.OnLogChanged;
    this._fileSystemWatcher.Deleted += this.OnLogChanged;
    this._fileSystemWatcher.Renamed += this.OnLogChanged;
    this._fileSystemWatcher.EnableRaisingEvents = true;
}

private void OnLogChanged(object source, FileSystemEventArgs e)
{
    switch (e.ChangeType) // <-- never gets here
    {
        case WatcherChangeTypes.Changed:
            this.UpdateLogView();
            break;
        case WatcherChangeTypes.Created:
        case WatcherChangeTypes.Deleted:
        case WatcherChangeTypes.Renamed:
        default:
            throw new NotImplementedException();
    }
}

Solution

  • I get the filesystem event when the StreamWriter is disposed, but not before.

    So dispose it.

    public class FlushingTextTraceListener : TextWriterTraceListener
    {
        public FlushingTextTraceListener(string filePath)
        {
            FilePath = filePath;
        }
        public String FilePath { get; set; }
    
        public override void Write(string message)
        {
            using (var sw = new StreamWriter(File.Open(FilePath, FileMode.Create, 
                FileAccess.Write, FileShare.Read)))
            {
                sw.Write(message);
            }
        }
    
        public override void WriteLine(string message)
        {
            using (var sw = new StreamWriter(File.Open(FilePath, FileMode.Create, 
                FileAccess.Write, FileShare.Read)))
            {
                sw.WriteLine(message);
            }
        }
    }