Search code examples
c#filesystemwatcher

Is filesystemwatcher the right way to monitor a file?


I know it’s a general question but I’m just opening this for discussion. I have to assume someone else must have done similar and I don’t want to do a lot of code to find out my solution wouldn’t work.

Here's what I have. A user will add a file to the database as an OLE object and associate some attitude to the file - project it's associated to, version etc. I’m using Access – customer choice not mine!

When they want to edit it, they will need to check it out. At this stage I want to monitor the file and when they save it, to restore it back to the database.

I'm thinking that file system watcher is my best way - monitor the change and save it back to the database when the change even is triggered and I can gain access to the file. If it's still opened the application will have it locked so I know that the user isn’t finish.

So in short my question is file system watcher the proper way to approach this? Anyone suggest anything else?

Thanks, Jim


Solution

  • As M4GNV5 says, FileSystemWatcher will work for this but it's a bit overkill. Using one is pretty involved in code as it's quite error-prone and needs very exact usage patterns to be successful. It also has a certain amount of overhead as it needs to hook into the filesystem driver in kernel mode.

    An alternate solution might use polling.

    FileInfo info = new FileInfo(filePath);
    DateTime oldTime = info.LastWriteTimeUtc;
    
    while(true)
    {
        do
        {
            await Task.Wait(1000);
            info.Refresh();
        } while(info.LastWriteTimeUtc == oldTime);
    
        try
        {
            using(Stream s = File.OpenRead(filePath))
            {
                // ok, file was modified and is unlocked. copy back.
            }
    
            break;
        }
        catch(IOException)
        {
            // file is locked, retry.
            oldTime = info.LastWriteTimeUtc;
        }
    }
    

    This first waits for the file's modify time to change, and then checks for it to be unlocked.