Mega Code Archive

 
Categories / Delphi / Files
 

How to get an Unique Identifier for a File or Folder

Title: How to get an Unique Identifier for a File or Folder Question: Everyone who creates a File/folder copy or move-function must check if a sourcefile/folder exists at the destination. But how can we proof that two files don't point to the same physical place? Windows 2000 and XP allows to mount any volume under a folder and so it's possible that the files at 'c:\data\*.*' are the same as under 'd:\*.*' for example. Answer: To get an unique ID from a File or Folder you can use the API-Function GetFileInformationByHandle respective the Infos got from those function. The combination of the FileIndex with the Serial-Number of the Volume identifies a File. To check if two files points to the same physical place just compare the two UIDs got from the function below. btw: the function also works for folders because it uses FILE_FLAG_BACKUP_SEMANTICS; But this Flag ONLY works on WinNT and higher. {----------------------------------------------------------------------------- Procedure: GetUFID Arguments: Filename: String Result: String Comments: Generate a Unique File-Identifier based upon Fileindex and the VolumeSerialnumber. If Filename doesn't exists result = ''; -----------------------------------------------------------------------------} Function GetUFID(Filename: String): String; Var hFile : tHandle; FileInfo : BY_HANDLE_FILE_INFORMATION; HighOrder, LowOrder : Int64; Begin // Get Filehandle ... Warning: Works only under WinNT and higher !!! hFile := CreateFile(pChar(Filename), 0, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); If hFile INVALID_HANDLE_VALUE then Begin If (GetFileInformationByHandle(hFile, FileInfo) = True) then Begin // Specifies the high-order word of a unique identifier associated with the file/folder HighOrder := FileInfo.nFileIndexHigh; // Specifies the low-order word of a unique identifier associated with the // file. This identifier and the volume serial number uniquely identify a file/folder LowOrder := FileInfo.nFileIndexLow; Result := Format('[%s-%s-%s]', [IntToStr(FileInfo.dwVolumeSerialNumber), IntToStr(LowOrder), IntToStr(HighOrder)]); End Else Result := ''; End else Result := ''; CloseHandle(hFile); //Release Handle End;