Get unique system ID for file in Windows RRS feed

  • Question

  • Hi

    I am working on a macro which I run in Excel to create a list of all the files found within a Windows folder and its subfolders. Over time the folder structure is modified and files are moved around. To deal with this, I would like to be able to include in my list an ID for each file, which remains the same when the file name or filepath is changed, but changes if the file is deleted and a new file created in the same location, with the same name.

    I am using VBA in Excel 2013


    Tuesday, October 3, 2017 9:50 AM

All replies

  • One method would be to use the GetFileInformationByHandle API function call to generate the unique ID:

    Const OFS_MAXPATHNAME = 128
    Const OF_CREATE = &H1000
    Const OF_READ = &H0
    Const OF_WRITE = &H1
    Private Type FILETIME
            dwLowDateTime As Long
            dwHighDateTime As Long
    End Type
            dwFileAttributes As Long
            ftCreationTime As FILETIME
            ftLastAccessTime As FILETIME
            ftLastWriteTime As FILETIME
            dwVolumeSerialNumber As Long
            nFileSizeHigh As Long
            nFileSizeLow As Long
            nNumberOfLinks As Long
            nFileIndexHigh As Long
            nFileIndexLow As Long
    End Type
    Private Type OFSTRUCT
            cBytes As Byte
            fFixedDisk As Byte
            nErrCode As Integer
            Reserved1 As Integer
            Reserved2 As Integer
            szPathName(OFS_MAXPATHNAME) As Byte
    End Type
    Private Declare Function GetFileInformationByHandle Lib "kernel32" (ByVal hFile As Long, lpFileInformation As BY_HANDLE_FILE_INFORMATION) As Long
    Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
    Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Function GetFileIdentifier(strFilePath) As String
    Dim lngFileHandle As Long
    lngFileHandle = OpenFile(strFilePath, OF, OF_READ)
    GetFileInformationByHandle lngFileHandle, FileInfo
    CloseHandle lngFileHandle
    GetFileIdentifier = CStr(FileInfo.nFileIndexHigh) & CStr(FileInfo.nFileIndexLow)
    End Function

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Tuesday, October 3, 2017 2:50 PM