Search code examples
c#.net-corefile-monitoring

Monitor changes in files on Windows using .NET Core 2.0


Before you send me links to here, here and maybe here bear with me.

I'd like to write a service that monitors changes of a given set of files and I started with the simplest thing writing console application that monitors directory in order to continue with my POC. However, I got stuck trying to extract the actual changes that were made. (Yes, I managed to handle the event in the FileSystemWatcher class, but as far as I see the API of the class I am unable to track the actual changes)

Do you know if there is a way to do so? Maybe without so much pain or unnecessary operations.

I am currently using .NET Core 2.0, but any version of .NET Core will do.

EDIT: The files I need to monitor are text based, basically I want to implement git diff functionality and report the changes.


Solution

  • The short answer is no, there is no API that will tell you which part of the file was modified. All you can get from the OS is a notification that a change has occurred to a file, not the nature or location of that change beyond what you get from the FileSystemWatcher.

    To detect the nature of the change you need to be able to compare the contents of the file before and after the change. In most cases you won't have access to the prior state of the file. You could use shadow copies to access the prior state of the file, but that has issues of its own.

    If you're monitoring only a small number of files then you can do some sort of fingerprinting - block level hashing for instance - to detect the location of the change. You'll still need a before and after to detect the particular change.

    That said...

    It is in principle possible to hook into the Windows APIs that are used to actually write data to the disk. I haven't tried this with .NET but I've used Detours in the past to do similar things. Be aware that API hooking is dangerous territory, and if you get it wrong you can kill your computer. Here be dragons. If you want to go this route I strongly suggest that you write your code with an eye towards minimising delays.