Search code examples
c#.netsecurityntfsfilesystemwatcher

.NET FileSystemWatcher to detect NTFS security changes


The .NET FileSystemWatcher's Changed event MSDN documentation says:

The Changed event is raised when changes are made to the size, system attributes, last write time, last access time, or security permissions of a file or directory in the directory being monitored.

However, when I try to use this class to capture NTFS security changes to a directory or a file the Changed event never fires.

Is there some way of accomplishing this without polling?


Solution

  • FileSystemWatcher does watch security permissions changes.
    You need to include NotifyFilters.Security flag, when you set FileSystemWatcher.NotifyFilter. I tried the code below, changed permissions for a file in Temp folder. The Changed event was triggered.

    public static void Main()
    {
        var fileSystemWatcher = new FileSystemWatcher("C:\\Temp", "*.*");
        fileSystemWatcher.NotifyFilter = NotifyFilters.Security;
        fileSystemWatcher.Changed += fileSystemWatcher_Changed;
        fileSystemWatcher.EnableRaisingEvents = true;
        Thread.Sleep(-1);
    }
    
    private static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
    {
    }