3

I'm trying to know if there are new files created in a given directory. I have next code:

private static void CreateWatcher()
    {
        //Create a new FileSystemWatcher.
        FileSystemWatcher watcher = new FileSystemWatcher();

        //Set the filter to all files.
        watcher.Filter = "*.*";

        //Subscribe to the Created event.
        watcher.Created += new FileSystemEventHandler(watcher_FileCreated);

        //Set the path 
        watcher.Path = path;

        //Enable the FileSystemWatcher events.
        watcher.EnableRaisingEvents = true;
    }

    private static void watcher_FileCreated(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("Nuevo archivo creado -> " + e.Name);        
    }

    public static void Main(string[] args)
    {
        CreateWatcher();
        CreateFiles();
        Console.Read();
    }

In CreatedFiles() function, I'm creating on the path three new files (one zip and two txt). It detects two txt files but not the same with the zip file. How can I solve that?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
  • 1
    My guess is that since `watcher` is a local in a method, it gets GCed and stops raising events. `Console.Read` might also block `Console.WriteLine`. – vcsjones Nov 11 '15 at 15:31
  • it works fine in my side. Can you share the CreateFiles code? Maybe you are using a thread or something that is not writing down the file? – wOOdy... Nov 11 '15 at 15:32
  • Now it show the tmp file. Why is doing that? – Jaime Menendez Llana Nov 11 '15 at 15:33
  • I've tried your code (creating the files from an external program) and it works correctly with a generic file as with the zip file, so it is probably caused by the code creating the files inside your project that has some problems with the Watcher. – Sabrina_cs Nov 11 '15 at 15:40
  • What do you use to create the zip file? The Tmp file is usually created by the zipper application before creating the zip, if your zip application creates the file and then renames it the create file will not be performed on the zip file so you won't receive the message. – Sabrina_cs Nov 11 '15 at 15:42
  • I'm using the library DoNetZip to create it – Jaime Menendez Llana Nov 11 '15 at 15:46
  • Show the creation function and also the notificationfilters!! – TaW Nov 11 '15 at 17:17
  • 2
    Possible duplicate of [Using FileSystemWatcher to monitor a directory](http://stackoverflow.com/questions/15017506/using-filesystemwatcher-to-monitor-a-directory) – Michael Freidgeim Mar 22 '17 at 21:32

1 Answers1

2

Suggest you take a look here. This has been addressed previously.

Using FileSystemWatcher to monitor a directory

Community
  • 1
  • 1
MDill33
  • 21
  • 2