In software development, ensuring data integrity and verifying whether a file has changed is a common requirement. One effective way to achieve this is by using the CRC32 (Cyclic Redundancy Check) hash, which is a popular method for detecting changes in files. In this blog post, we will explore a Delphi function that calculates the CRC32 hash of a file, allowing you to detect any modifications easily.
Let's dive into the function:
function PACalculateCRC32FromFile(const FileName: string): string;
// Calculate FAST CRC32 File Hash (e.g. for the purpose of detecting if a file has changed)
var
IdCRC32: IdHashCRC.TIdHashCRC32; // Declare a variable to hold the CRC32 hash object
FileStream: System.Classes.TFileStream; // Declare a variable to hold the file stream
CRC32: Cardinal; // Declare a variable to hold the CRC32 value
begin
IdCRC32 := TIdHashCRC32.Create; // Create an instance of the CRC32 hash object
try
// The file specified by FileName is opened in read-only mode with shared deny-write access.
// This ensures that the file can be read while preventing other processes from writing to it:
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); // Open the file for reading
try
CRC32 := IdCRC32.HashValue(FileStream); // Calculate the CRC32 value of the file
// The computed CRC32 value, which is a Cardinal type, is converted to an 8-character hexadecimal string.
// This makes the result more readable and suitable for comparison purposes:
Result := IntToHex(CRC32, 8); // Convert the CRC32 value to a hexadecimal string
finally
FileStream.Free; // Ensure the file stream is freed even if an exception occurs
end;
finally
IdCRC32.Free; // Ensure the CRC32 hash object is freed even if an exception occurs
end;
end;