How to get the main stream file descriptor?

I have an application that works with snapshots of physical memory (e.g. VMware VMEM files). Among other things, it can read processes / modules from a snapshot using a virtual address rather than a physical address. This includes restoring the 4KB module at a time through the page table, which in turn means many calls to the Stream Seek () method.

For reasons I'm not sure about, these calls to action () are swamping down. As a result, I'm looking for a way around them — or at least a way to implement managed Seek (). My best guess is PInvoke SetFilePointer and work with it directly, but for this I need to get IntPtr / SafeFileHandle for the stream. I have a few limitations:

  • The API I'm working with is limited to .NET 3.5, so unfortunately, MemoryMappedFile is not an option.

  • I can’t use FileStream (which already has a SafeFileHandle private field that can be accessed with reflection) or PInvoke CreateFile () to get the snapshot in another way - the API includes BinaryReader, which has an exclusive snapshot lock.

Of course, unlike FileStream, neither BinaryReader nor its underlying Stream have a link to a file descriptor. But of course you need to exist? In which case, how do I get it?

+5
source share
2 answers

Stream, . , Stream, - FileStream, , MemoryStream, , .

( a SafeFileHandle) BinaryReader, Stream FileStream, private SafeFileHandle _handle, :

SafeFileHandle sfh = (SafeFileHandle)typeof(FileStream).GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue((FileStream)YOUR_BINARY_READER.BaseStream)

: SetFilePointer(), MemoryMappedFile . , , ( ).

+3

BinaryReader FileStream, BaseStream , FileStream, SafeFileHandle . - :

FileStream stream = (FileStream)(reader.BaseStream);
//use stream.SafeFileHandle
+1

All Articles