0

Here's the scenario:

Some application reads contents of a file. It does so by opening it for shared reading, and then at some point closing it (as I've seen it in Procmon.exe, see image). Right after the file is closed, I want to run my own code editing that file.

The only answer I've found so far is looping File.Open() in a try block and firing an event when it throws an exception, and that won't work for shared read access, let alone how ugly it is.

Is there a package or a custom class I can use?

Edit: The application doesn't lock the file. To make sure, I tried running File.OpenRead(); Thread.Sleep(); before the application launch, and it loaded the file as intenteded. It crashed with File.OpenWrite() though, so I'm convinced there are no locks placed by the application.

Edit: Tried writing some test programs with Restart Manager API implementations, none of them seem to be capturing non-locking reading.

  • Checkout [FileWatcher](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.8) – Matt Rowland Jul 19 '19 at 20:32
  • @MattRowland Already tried looping `WaitForChanged`, it updated on write events but not on read events. – TheLeftExit Jul 19 '19 at 20:35
  • Possible duplicate of [Getting notified when a file lock is released](https://stackoverflow.com/questions/36205450/getting-notified-when-a-file-lock-is-released) – Matt Rowland Jul 19 '19 at 20:37
  • @MattRowland The process isn't locking the file while reading from it. I'm not very familiar with terminology of this, but I believe that's the case when `Procmon.exe` shows `Desired Access: Generic Read; ShareMode: Read, Write` on file opening event. – TheLeftExit Jul 19 '19 at 20:48
  • Gotcha. You would have to constantly watch the security logs and have auditing turned on. The code for that wouldn't fit in an answer here. – Matt Rowland Jul 19 '19 at 20:52
  • @MattRowland In fact, I thought of this question while monitoring process activity with `Procmon.exe` and having an idea of selectively hooking my own code to events that it tracked. It might be messy in its implementation, but if it's done natively, there's probably a way to recreate it in C#, or at least link to native code. – TheLeftExit Jul 19 '19 at 20:58

0 Answers0