Is it possible when a file operation is called somehow - like open or close - that I can handle it before the request proceeds by the operating system and if possible cancel it by .NET? If .NET has no abilities like that, how can I do this?
4 Answers
What your asking to do can be done. Virus Scanners, for example, do it all the time. You can easily monitor file activity with Process Monitor. You can also do it programmically in C# using the FileSystemWatcher Class. But trying to prevent a program from opening up or trying to stop a program from accessing the file can not be done in C#. You will need to use either C or C++. You need to create a File System Filter Driver. It is a complex thing to build but its exactly what you need. To quote MSDN:
A file system filter driver intercepts requests targeted at a file system or another file system filter driver. By intercepting the request before it reaches its intended target, the filter driver can extend or replace functionality provided by the original target of the request. Examples of file system filter drivers include anti-virus filters, backup agents, and encryption products.

- 47,519
- 50
- 171
- 296
You can hook the Windows API if you want to. Check out this way to do that in .NET/C#:

- 30,738
- 21
- 105
- 131

- 319
- 1
- 5
Sysinternals offers a free tool called Process Monitor, one function of which is to attach to arbitrary Windows processes (including .NET applications) and capture system calls, including file open, close, read, etc.
You can download it at the Process Monitor Download Page.
EDIT
As I re-read your question, I see that you're asking about intercepting and possibly cancelling such operations. I believe the FileSystemWatcher
class will be your best bet, although I don't think it can cancel file operations unilaterally - you'd need to build some kind of cooperative mechanism to signal the caller to abort its operation.

- 6,023
- 1
- 25
- 40
I'm pretty sure you've got to get into the kernel on that kind of operation and I'm pretty sure that means you'll need to code in C. Look at File System Drivers.
UPDATE: this SO link may help.
UPDATE: added a google search for Windows File System Drivers
ALSO What is a good resource to get started with Windows file system driver development?

- 21,522
- 8
- 49
- 87
-
@JamesWilkins it must have been temporary. Both links just worked for me. Best – kenny Oct 10 '17 at 21:06