Delphi 6:如何更改创建文件日期(=文件创建日期)?

11

我已经在谷歌和这里搜索了几个小时,但是我找不到解决办法。

我想要在DELPHI 6中更改“创建时间”(即创建文件的时间戳),而不是“修改时间”(只需要使用“FileSetDate()”调用)或“上次访问时间”。

我应该如何操作?

所指内容的图片...

2个回答

10
调用Windows API函数SetFileTime。如果您只想修改创建时间,请将lpLastAccessTimelpLastWriteTime参数设置为nil
您需要调用CreateFile或其中一个Delphi包装器来获取文件句柄,因此这不是最方便的API。
通过将API调用封装在一个帮助函数中,该函数接收文件名和TDateTime。该函数应管理获取和关闭文件句柄的低级细节,并将TDateTime转换为FILETIME,从而使您的生活更轻松。
我会这样做:
const
  FILE_WRITE_ATTRIBUTES = $0100;

procedure SetFileCreationTime(const FileName: string; const DateTime: TDateTime);
var
  Handle: THandle;
  SystemTime: TSystemTime;
  FileTime: TFileTime;
begin
  Handle := CreateFile(PChar(FileName), FILE_WRITE_ATTRIBUTES,
    FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL, 0);
  if Handle=INVALID_HANDLE_VALUE then
    RaiseLastOSError;
  try
    DateTimeToSystemTime(DateTime, SystemTime);
    if not SystemTimeToFileTime(SystemTime, FileTime) then
      RaiseLastOSError;
    if not SetFileTime(Handle, @FileTime, nil, nil) then
      RaiseLastOSError;
  finally
    CloseHandle(Handle);
  end;
end;

我不得不添加FILE_WRITE_ATTRIBUTES的声明,因为它在Delphi 6 Windows单元中不存在。


问题时间为中欧时间和UTC+1。 - mih
我可以确认。 (德国时间) 你需要将DateTimeToSystemTime(DateTime, SystemTime)更改为DateTimeToSystemTime(DateTimeToUTC(DateTime), SystemTime)。一个可能的DateTimeToUTC实现可以在这里找到: https://www.delphipraxis.net/207745-utc-local-time.html - Daniel Marschall

7

基于FileSetDate,您可以编写类似的例程:

function FileSetCreatedDate(Handle: Integer; Age: Integer): Integer;
var
  LocalFileTime, FileTime: TFileTime;
begin
  Result := 0;
  if DosDateTimeToFileTime(LongRec(Age).Hi, LongRec(Age).Lo, LocalFileTime) and
    LocalFileTimeToFileTime(LocalFileTime, FileTime) and
    SetFileTime(Handle, @FileTime, nil, nil) then Exit;
  Result := GetLastError;
end;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接