Search code examples
c++winapifilesystemsntfsusn

How to have a unique ID for all files in all disks, using WinApi / USN / MasterFileTable?


I'm using the NTFS MasterFileTable / USN journal of a few disk/partitions (C:, D:, E:, F:, etc), and I'd like to use a unique ID for each file/directory.

While I'm reading the USN_RECORD (also called PUSN_RECORD), there is this int64:

DWORDLONG     FileReferenceNumber;

that is a unique file/directory identifier, unique at least in the current partition.

But there could be collisions:

  • a file in C: could have FileReferenceNumber 1932847
  • another file in D: could have FileReferenceNumber 1932847 too!

I'd like to avoid having to use such a big thing as an int128 (that would be the 64 bits of FileReferenceNumber + 5 bits for the drive letter C:, D:, E:, ..., Z:).

I also would like to avoid having to use a pair (char DriveLetter, DWORDLONG FileReferenceNumber) to identify a file in the computer.

How to use a 64-bit int to code FileReferenceNumber + drive letter?

Is it possible because FileReferenceNumber has a few free unused bits?

If not, how would you handle this?


Solution

  • You must use a pair of FileReferenceNumber/FileID and "volume something". You can mount a volume in a folder so you cannot really use the drive letter.

    Ideally "volume something" is the volume GUID path but you can use the volume serial number if size is important. Note: Not all volumes have a GUID.

    For NTFS you can get it from GetFileInformationByHandle and build a 32-bit+64-bit pair. For ReFS you need GetFileInformationByHandleEx and build a 64-bit+128-bit pair.