How to detect that file is about to be modified in c#?

127 Views Asked by At

My .Net application monitors files in specified directory. If any file is about to be modified I need to backup that file.

My goal is to avoid backing up all files in the directory. I want only to backup files that will be modified, it is only a tiny percentage of all files in a folder.

As far as I see the .Net FileSystemWatcher can only detect that file is already modified, so it is too late for me to backup the file at that moment.

How do I detect the moment when the file is about to be modified, so I can backup it?

1

There are 1 best solutions below

3
On

If theres no easy way of intetcepting the write operating (and I'm pretty sure there isn't, not without writing drivers like some people have commented) you could cheat and use a combination of shaddow coppies and file system watcher. Start with a shadow copy, when the file system watcher detects change, restore the shadow copy, and then do whatever you were intending after.

I know its not a solution just a work around, but youd end up with the same result, a file with the original version after a save.