Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating File Handles in C#

I would like to know whether it is possible to enumerate file handles in c#, maybe using Win32API? This is easily done for window and process handles, but it seems that it is not possible for file handles.

While some functionality is offered by NtQuerySystemInformation, this is being phased out and therefore it is not recommended to use such a method.

like image 308
steffar Avatar asked Apr 09 '10 23:04

steffar


1 Answers

Well, you know it is possible, SysInternals' Handle utility does it. NtQueryInformation isn't going to be phased out, it is an essential low-level interface between Win32 and the "real" operating system.

What is however never going to happen is that the NtQueryInformation arguments that allow iterating handles is going to be documented. Because it doesn't stop just there, some muppet is going to use it to call CloseHandle() on a file that s/he doesn't want to be locked. Which is a very good way to destroy your hard disk content.

The process that owned the handle doesn't know the handle is closed. It will just keep writing to it, probably completely ignoring the "it didn't work" return code from WriteFile(). Which is harmless until the program opens another handle, getting the same value back as the one that was closed earlier. Now it starts writing a mix of garbage (intended for the previous handle) and new data to the handle. Utterly destroying the content of whatever it is writing to. Spin up the backup tapes if that's something like a mission critical database.

like image 134
Hans Passant Avatar answered Sep 19 '22 18:09

Hans Passant