Search code examples
c#.netfilesystemwatcher

How can i use FileSystemWatcher to watch for file size changes?


A method that set the watcher:

private void WatchDirectory()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = userVideosDirectory;
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Filter = "*.mp4";
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
        }

And the event that tell if there is any changes:

private void OnChanged(object source, FileSystemEventArgs e)
    {
        dirchanged = true;
    }

Now i'm checking if there is a new file in the directory. But now i also want to watch and check if this new last created file size changing. And when the size of the file is not changing anymore give a message like "The file is ready".

How can i watch for the file size in real time untill there is no more changes ?


Solution

  • This is quite a common problem when using the file system to communicate between two applications. In my experience it works best if you also have a marker file indicating that the "real" file was written completely:

    SystemA: Writes file theRealFile.txt
    SystemA: Writes file theRealFile.rdy (0byte)
    SystemB: Watches for .rdy files and then reads theRealFile.txt