Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to trace file operations with .NET?

Tags:

c#

.net

file

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?

like image 371
Halil Ibrahim Avatar asked May 10 '12 20:05

Halil Ibrahim


3 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.

like image 85
Icemanind Avatar answered Nov 14 '22 12:11

Icemanind


You can hook the Windows API if you want to. Check out this way to do that in .NET/C#:

EasyHook Windows API

like image 3
negEntropy Avatar answered Nov 14 '22 12:11

negEntropy


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.

like image 2
Ben Avatar answered Nov 14 '22 11:11

Ben