Get file info from NTFS-MFT reference number

坚强是说给别人听的谎言 提交于 2019-12-01 17:19:47

问题


In my C# application, I already have a way to examine the file system but I would like to take advantage of reading from the Master File Table (MFT) because it is so much faster. I understand that 1) it is a proprietary specification and therefore subject to change without notice, and 2) it is only accessible when the application is running under administrative privileges.

I managed to read the Master File Table via this code. From the MFT query, I get a file name and a so-called file reference number. What I can't find is how to transition to a .NET FileInfo object, or even to a Windows API file handle, so that I can get more information about the files/folders in question, like: file size, full path, date stamps, etc.


回答1:


There's two straightforward approaches you can take to open the file when you're lurking around in the MFT - You can call OpenFileByID with that file reference number (Vista and higher), or you can build the fully qualified file name by traversing the list you built when reading the MFT and then calling the CreateFile with the assembled name.

You want to get the handle from CreateFile or OpenFileByID into a SafeFileHandle:

[DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
internal static extern SafeFileHandle CreateFile( string lpFileName, EFileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile );

[DllImport( "kernel32.dll", SetLastError = true )]
internal static extern SafeFileHandle OpenFileById( IntPtr volumeHandle, ref FileIdDescriptor lpFileId, uint dwDesiredAccess, uint dwShareMode, uint lpSecurityAttributes, uint dwFlagsAndAttributes );

Once you have the SafeFileHandle (and you've checked that it's valid), you can pass it to a FileStream constructor and read/write the file like normal.

Every file is represented in the MFT, but there are caveats. For example, a single file can be in the file hierarchy in multiple places, yet there is a single MFT entry for all of 'em - these are the so-called hard links (they're not copies - there are multiple entry points to a file - headaches abound). There are thousands of these. There are APIs for interrogating the hard links, but it gets ugly.



来源:https://stackoverflow.com/questions/24724343/get-file-info-from-ntfs-mft-reference-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!