问题
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