Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are FileSystemWatcher Attribute changes detected on Windows 7 but not Windows 8?

Tags:

c#

.net

windows-8

I have some code that uses FileSystemWatcher to monitor file changes outside of my application.

On Windows 7, using .NET 4, the below code would detect when a file had been edited and saved in an application like Notepad, while my app was running. However, this logic isn't working using .NET 4 on Windows 8. Specifically, the FileSystemWatcher's Changed event never fires.

public static void Main(string[] args) {     const string FilePath = @"C:\users\craig\desktop\notes.txt";      if (File.Exists(FilePath))     {         Console.WriteLine("Test file exists.");     }      var fsw = new FileSystemWatcher();     fsw.NotifyFilter = NotifyFilters.Attributes;     fsw.Path = Path.GetDirectoryName(FilePath);     fsw.Filter = Path.GetFileName(FilePath);      fsw.Changed += OnFileChanged;     fsw.EnableRaisingEvents = true;      // Block exiting.     Console.ReadLine(); }  private static void OnFileChanged(object sender, FileSystemEventArgs e) {     if (File.Exists(e.FullPath))     {         Console.WriteLine("File change reported!");     } } 

I understand that I can alter the NotifyFilter to also include NotifyFilters.LastWrite, which can solve my problem. However, I want to understand why this code worked on Windows 7 but now fails to fire the Changed event on Windows 8. I'm also curious to know if there's a way to restore my Windows 7 FileSystemWatcher behavior when running in Windows 8 (without changing the NotifyFilter).

like image 800
Craig Avatar asked Nov 30 '12 00:11

Craig


2 Answers

Check the archive bit on the file before/after you edit it. Your code is only searching for Attributes changes, so my guess is that Windows 7 is updating the Archive bit on the file, and windows 8 is not.

like image 132
ChristopherBrown Avatar answered Oct 06 '22 18:10

ChristopherBrown


There are too many comments everywhere, I will just add an answer to verify that you are aware of the following issues:

  • get filesystemwatcher events to occur on main UI thread (look for Hans Passant's answer)
  • WPF - Cannot change a GUI property inside the OnChanged method (fired from FileSystemWatcher)

Apparently the problem is that the event is raised on a background thread, and you need to marshal the call back to the UI thread.

I have experienced a lot of trouble with the FileSystemWatcher class, and decided not to use it as you can see me describe here: https://stackoverflow.com/a/22768610/129130 . It is possible, however, that the problems I experienced were due to thread synchronization issues and / or hardware issues.

like image 41
Stein Åsmul Avatar answered Oct 06 '22 17:10

Stein Åsmul