写了两个函数:
type
TFileTimeType = (fttCreation, fttLastAccess, fttLastWrite);
//分别对应文件创建时间,访问时间,修改时间
function GetFileDateTime(const FileName: string; FileTimeType: TFileTimeType): TDateTime;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
DosDateTime: Integer;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
case FileTimeType of
fttCreation:
FileTimeToLocalFileTime(FindData.ftCreationTime, LocalFileTime);
fttLastAccess:
FileTimeToLocalFileTime(FindData.ftLastAccessTime, LocalFileTime);
fttLastWrite:
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
end;
if FileTimeToDosDateTime(LocalFileTime, LongRec(DosDateTime).Hi,
LongRec(DosDateTime).Lo) then
begin
Result := FileDateToDateTime(DosDateTime);
Exit;
end;
end;
end;
Result := -1;
end;
function SetFileDateTime(const FileName: string; FileTimeType: TFileTimeType; DateTime: TDateTime): Integer;
var
Handle: THandle;
LocalFileTime, FileTime: TFileTime;
DosDateTime: Integer;
I : TFileTimeType;
FileTimes: array[TFileTimeType] of Pointer;
begin
Result := 0;
DosDateTime := DateTimeToFileDate(DateTime);
Handle := FileOpen(FileName, fmOpenWrite or fmShareDenyNone);
if Handle <> INVALID_HANDLE_VALUE then
begin
for I := fttCreation to fttLastWrite do
FileTimes := nil;
DosDateTimeToFileTime(LongRec(DosDateTime).Hi, LongRec(DosDateTime).Lo, LocalFileTime);
LocalFileTimeToFileTime(LocalFileTime, FileTime);
FileTimes[FileTimeType] := @FileTime;
if SetFileTime(Handle, FileTimes[fttCreation], FileTimes[fttLastAccess],
FileTimes[fttLastWrite]) then Exit;
end;
Result := GetLastError;
end;
使用:
1、获取文件创建时间:
ShowMessage(DateTimeToStr(GetFileDateTime('c:/key.txt',fttLastWrite)));
2、设置文件修改时间:
SetFileDateTime('c:/key.txt',fttLastWrite, datetimepicker1.DateTime);