System.IO.FileSystemWatcher: When are events fired? Before or after completion of operation? RRS feed

  • Question

  • I'm wondering whether a FileSystemWatcher object fires its events before or after a file system operation has completed.

    I need to know this information because I want to process files after they have been added to a directory. So the file must have been fully written and the originator's file handle must have been closed, so I will be able to move/rename the file before processing it.

    Other subscribers to a FileSystemWatcher object's events might just want to know when a directory's contents have changed in order to update their view ASAP.

    So both scenarios, firing right at the beginning or firing after completion of a file system operation, are valid.

    Can someone please enlighten me on when the FileSystemWatcher events will fire? Before or after completion of a file system operation?

    Vote here for a Microsoft Connect feedback channel on Windows - and win a better Windows!
    Vote here for a consistent keyboard shortcut support in Visual Studio and other Microsoft products!

    • Edited by BetterToday Wednesday, August 15, 2012 12:19 PM
    Wednesday, August 15, 2012 12:15 PM


  • The FileSystemWatcher handle low level operations on files. Your problem is that your code need to wait for the file to become available for read/move operation. And you have to wait the file become closed by other processes.

    So I deeply suggest you to handle an added files list in witch you add new files on FileSystemWatcher.Created event. On Deleted and Renamed event, you have to update the list if the original file is in it. On Changed event, you can try your operations but without guaranties of success.

    The LastWrite is generally updated when the file is closed (don't rely on LastAccess, some file system doesn't have it and NTFS is slow to update it to optimize disk access: up to one hour).

    You have to kown that many things may happen on added files (for example your antivirus will probably scan it). So you do not have a guaranty that your operation on added files will succeed on the first try. So you need a background timer or pooling thread that regularly try to launch our operations on new files and remove them from the added file list only in case of success.

    There are many samples and articles on internet about FileSystemWatchers that can help you:



    If you decide to code an easy to use, reusable AddedFileWatcher component by yourself with a TryProcessAddedFile event. You may interest many coders (including me).

    Renaud Bancel

    Wednesday, August 15, 2012 4:10 PM