简体   繁体   中英

Last write FILETIME always returning current time

I need to compare a file's last modified time to a date time stored in a database. I initially looked at this question to get started.

I am currently getting the FILETIME for the last write of the file, converting it to a SYSTEMTIME . Then I use that SYSTEMTIME to create a TDateTime object that I can use for my comparison. However, the FileModifiedDT variable, is always coming out to be the current time, despite the file having been modified previously.

FILETIME lastWriteTime;

String * FileNamePtr = new String( FileName );

GetFileTime( FileNamePtr, NULL, NULL, &lastWriteTime );

SYSTEMTIME systemTime;
FileTimeToSystemTime( &lastWriteTime, &systemTime );

TDateTime * FileModifiedDT = new TDateTime( systemTime.wYear, systemTime.wMonth,
                                            systemTime.wDay, systemTime.wHour,
                                            systemTime.wMinute, systemTime.wSecond,
                                            systemTime.wMilliseconds );

Am I missusing GetFileTime in some way? Is there a better way I should go about this?

The error is

String * FileNamePtr = new String( FileName );
GetFileTime( FileNamePtr, NULL, NULL, &lastWriteTime );

According to the documentation , the first argument has to be a file handle created by CreateFile and nothing else.

Thus you need something like this:

HANDLE fileHandle = CreateFile(
  FileName, //LPCTSTR
  GENERIC_READ,
  FILE_SHARE_READ,
  NULL,
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL,
  NULL
);

if ( fileHandle != INVALID_HANDLE )
{
    GetFileTime( fileHandle, NULL, NULL, &lastWriteTime );
    CloseHandle( fileHandle );
}
else
{
    // error, do something else...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM