Search code examples
c#filesystemwatcher

FileSystemWatcher not firing .Created on FileInfo.Create( )


I'm attempting to use the FileSystemWatcher object to watch directories for when new files are created to maintain a combo-box of files present in real time.

Unfortunately, files created in code are not firing the event handler attached to the Created event.

Why is this not working, and what can I do to make it work, using the FileSystemWatcher object? ( I've seen this and would rather not have to depend on an external library to make this work ).

I have seen the FileSystemWatcher work when I right-click -> create new file, but I need it to work when the program calls .Create( ) on a FileInfo object.

In compliance with the Minimal, Complete, and Verifiable Example requirements:

using System;
using System.IO;
using System.Security.Permissions;

namespace MCVEConsole {
    class Program {
        [PermissionSet( SecurityAction.Demand, Name = "FullTrust" )]
        static void Main( string[] args ) {
            DirectoryInfo myDirectory = new DirectoryInfo(
                Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments )
                ).CreateSubdirectory( "MCVEConsole" );
            FileSystemWatcher fSW = 
                new FileSystemWatcher( myDirectory.FullName, "*.txt" ) {
                    NotifyFilter = 
                        NotifyFilters.CreationTime | 
                        NotifyFilters.LastAccess | 
                        NotifyFilters.LastWrite
                };

            fSW.Created += new FileSystemEventHandler( _Changed );
            fSW.Deleted += new FileSystemEventHandler( _Changed );
            fSW.EnableRaisingEvents = true;

            new FileInfo(
                Path.Combine( myDirectory.FullName, "foo.txt" ) ).Create( ).Close( );

            void _Changed( object sender, FileSystemEventArgs e ) =>
                Console.WriteLine( "bar" );

            Console.WriteLine( "Press any key to continue..." );
            Console.ReadKey( );
        }
    }
}

The reason for the [PermissionSet] attribute is because I noticed it here, and thought that it may be the problem ( It was not ).


Solution

  • Try NotifyFilters.FileName. That's what I've had to add to see new files being created. Not what I expected but gave the result I needed.