缘起:
取文件真实创建时间_精易论坛
图:
代码【带注释】:
[Delphi] 纯文本查看 复制代码 function GetPETimestamp(const FileName: string): TDateTime;
var
FileBase: Pointer;
DosHeader: PImageDosHeader;
NTHeaders: PImageNtHeaders;
TimeStamp: DWORD;
begin
Result := 0;
var FileHandle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if FileHandle = INVALID_HANDLE_VALUE then
Exit;
try
//创建文件映射 因为PE文件可能会很大
var FileMapping := CreateFileMapping(FileHandle, nil, PAGE_READONLY, 0, 0, nil);
if FileMapping = 0 then
Exit;
try
//读取映射文件
FileBase := MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 0);
if FileBase = nil then
Exit;
try
//读取Dos头
DosHeader := PImageDosHeader(FileBase);
//如果Dos头不正确 退出不是PE文件
if DosHeader^.e_magic <> IMAGE_DOS_SIGNATURE then
Exit;
//读取NT头
NTHeaders := PImageNtHeaders(PByte(FileBase) + DosHeader^._lfanew);
//NT头不正确 退出
if NTHeaders^.Signature <> IMAGE_NT_SIGNATURE then
Exit;
//NT头DOS头都正确 是PE文件。从NT头读取PE文件的链接时间
TimeStamp := NTHeaders^.FileHeader.TimeDateStamp;
//Unix转换为可读的时间
Result := UnixToDateTime(TimeStamp,False);
finally
UnmapViewOfFile(FileBase);
end;
finally
CloseHandle(FileMapping);
end;
finally
CloseHandle(FileHandle);
end;
end;
|