File signatures are unique byte sequences at the beginning of a file that can help identify its type. You can read the first few bytes of a file and compare them with known signatures.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function GetFileTypeBySignature(const FileName: string): string; var FileStream: TFileStream; Signature: array[0..1] of AnsiChar; begin Result := ‘Unknown File Type’; try FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try FileStream.ReadBuffer(Signature, SizeOf(Signature)); if (Signature[0] = ‘B’) and (Signature[1] = ‘M’) then Result := ‘BMP Image’ else if (Signature[0] = #137) and (Signature[1] = ‘P’) then Result := ‘PNG Image’ // Add more signature checks as needed else Result := ‘Unknown File Type’; finally FileStream.Free; end; except // Handle exceptions as needed end; end; |
In this example, the signatures for BMP and PNG images are checked. You can extend the list with additional file types.
Leave a Reply