Search code examples
delphidatetimefile-attributes

Delphi: SetFileDate creates wrong LastWriteTime (Summer/Wintertime)


i am downloading a file from my server (i only get the bytes and a DateTime for the lastwritetime attribute) and after downloading the data i create a new file on my local machine and want to set the lastwritetime attribute. For this i am using the following method:

procedure SetFileDate(const FileName: string; NewDate: TDateTime);
var
    FileDate, FileHandle: Integer;
begin
    try
        FileDate := DateTimeToFileDate(NewDate);

        FileHandle := FileOpen(FileName, fmOpenReadWrite or fmShareDenyWrite);
        if FileHandle > 0 then
            begin
                FileSetDate(FileHandle, FileDate);
                FileClose(FileHandle);
            end;
    except
        begin
            // ERROR Log
            err.Msg('FileReqThrd.SetFileDate');
        end;
    end;
end;

For the 'NewDate' parameter i use the DateTime which i get from my server. I tried to convert the DateTime from the server like this to get the valid lastwritetime (i am requesting the data from a WCF this is why i am converting it to UTCDateTime, the untouched data from the WCF service is TXSDateTime):

TDateTime cloudFileDateTime := StrToDateTime(DateTimeToStr(cloudDownloadResult.FileCloudData.Lastwritetime.AsUTCDateTime));

But in the end my lastwritetime attribute from files which have a lastwritetime in the wintertime period are wrong with -1h.

I hope you understand my problem and can give me an idea how to solve it.

Best regards


Solution

  • The easiest way to do this is to call TFile.SetLastWriteTimeUtc from the System.IOUtils unit.

    TFile.SetLastWriteTimeUtc(FileName, 
        DateTimeUtc);
    

    If this function is not available use the Win32 API function SetFileTime.

    You'll also need DateTimeToSystemTime and then SystemTimeToFileTime in that scenario.