以前一个大富翁的代码:
type
TFileTimeType = (fttCreation, fttLastAccess, fttLastWrite);
function GetFileDateTime(const FileName: string; FileTimeType: TFileTimeType): string;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
DosDateTime: Integer;
begin
Result := '';
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
Result := FormatDateTime('yyyy-mm-dd hh:mm:ss', FileDateToDateTime(DosDateTime));
end;
end;
end;
function SetFileDateTime(const AFileName: string; FileTimeType: TFileTimeType; ADateTime: TDateTime): Integer;
var
FHandle: HFile;
LocalFileTime, AFileTime: TFileTime;
DosDateTime: Integer;
I : TFileTimeType;
FileTimes: array[TFileTimeType] of Pointer;
begin
Result := 0;
DosDateTime := DateTimeToFileDate(ADateTime);
FHandle := FileOpen(AFileName, fmOpenWrite or fmShareDenyNone);
try
if FHandle <> INVALID_HANDLE_VALUE then
begin
for I := fttCreation to fttLastWrite do
FileTimes := nil;
DosDateTimeToFileTime(LongRec(DosDateTime).Hi, LongRec(DosDateTime).Lo, LocalFileTime);
LocalFileTimeToFileTime(LocalFileTime, AFileTime);
FileTimes[FileTimeType] := @AFileTime;
if SetFileTime(FHandle, FileTimes[fttCreation], FileTimes[fttLastAccess],
FileTimes[fttLastWrite]) then
Exit;
end;
finally
FileClose(FHandle);
end;
Result := GetLastError;
end;
使用:
1、获取文件创建时间:
ShowMessage(GetFileDateTime('c:/key.txt',fttLastWrite));
2、设置文件修改时间:
SetFileDateTime('c:/key.txt',fttLastWrite, datetimepicker1.DateTime);