首页  编辑  

如何修改目录建立时间

Tags: /超级猛料/Stream.File.流、文件和目录/目录/   Date Created:

使用CreateFile打开目录时,一般只能指定为GENERIC_READ,不能为GENERIC_WRITE。不过在NT下,可以在Flag中加入FILE_FLAG_BACKUP_SEMANTICS标志,就可以以写模式打开目录,从而可以修改目录的时间属性。

hFile := CreateFile(PChar(FileName),

                   GENERIC_READ or GENERIC_Write,

                   FILE_SHARE_READ or FILE_SHARE_Write,

                   nil,

                   OPEN_EXISTING,

                   FILE_ATTRIBUTE_NORMAL or FILE_FLAG_BACKUP_SEMANTICS,

                   0);

************************

{ Sets the time for both files and directories }

{ for NT }

function NT_SetDateTime(FileName: string; dtCreation, dtLastAccessTime, dtLastWriteTime: TDateTime): Boolean;

// by Nicholas Robinson

var

 hDir: THandle;

 ftCreation: TFiletime;

 ftLastAccessTime: TFiletime;

 ftLastWriteTime: TFiletime;

 function DTtoFT(dt: TDateTime): TFiletime;

 var

   dwft: DWORD;

   ft: TFiletime;

 begin

   dwft := DateTimeToFileDate(dt);

   DosDateTimeToFileTime(LongRec(dwft).Hi, LongRec(dwft).Lo, ft);

   LocalFileTimeToFileTime(ft, Result);

 end;

begin

 hDir := CreateFile(PChar(FileName),

                    GENERIC_READ or GENERIC_WRITE,

                    0,

                    nil,

                    OPEN_EXISTING,

                    FILE_FLAG_BACKUP_SEMANTICS,

                    0);

 if hDir <> INVALID_HANDLE_VALUE then  

 begin

   try

     ftCreation       := DTtoFT(dtCreation);

     ftLastAccessTime := DTtoFT(dtLastAccessTime);

     ftLastWriteTime  := DTtoFT(dtLastWriteTime);

     Result := SetFileTime(hDir, @ftCreation, @ftLastAccessTime, @ftLastWriteTime);

   finally

     CloseHandle(hDir);

   end;

 end

 else

   Result := False;

end;

procedure TForm1.Button2Click(Sender: TObject);

begin

 NT_SetDateTime('c:\temp\MyFolder', now, now, now);

end;