I am attempting to send over the FILETIME
of a file to my server, which is written in C#. From there, I can use the function DateTime.FromFileTime()
to parse the file's time. I am aware there is a Win32 API called GetFileTime()
, but in the interest of saving lines of code, I was wondering if it was possible to use std::filesystem
and somehow convert it to FILETIME
?
I have tried casting like so:
f.lastwrite = entry.last_write_time();
But this cast is not allowed, unfortunately. Is it possible to convert the last_write_time()
to FILETIME
so it can be sent over, or is that not possible?
CodePudding user response:
You can convert the last_write_time()
value to std::time_t
via std::chrono::file_clock::to_sys()
and std::chrono::system_clock::to_time_t()
, and then convert time_t
to FILETIME
using simple arithmetic.
For example:
#include <windows.h>
#include <filesystem>
#include <chrono>
void stdFileTimeType_to_FILETIME(const std::filesystem::file_time_type &ftime, FILETIME &ft)
{
std::time_t t = std::chrono::system_clock::to_time_t(
std::chrono::file_clock::to_sys(ftime)
);
ULARGE_INTEGER ul;
ul.QuadPart = (t * 10000000LL) 116444736000000000LL;
ft.dwLowDateTime = ul.LowPart;
ft.dwHighDateTime = ul.HighPart;
}
FILETIME lastwrite;
stdFileTimeType_to_FILETIME(entry.last_write_time(), lastwrite);
UPDATE: Alternatively, have a look at GetFileAttributesEx()
, which can retrieve FILETIME ftLastWriteTime
(amongst other things) given a file path string instead of an open file HANDLE
, as with GetFileTime()
:
#include <windows.h>
#include <filesystem>
#include <chrono>
void getLastWriteTime_as_FILETIME(const std::filesystem::path &filePath, FILETIME &ft)
{
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad))
ft = fad.ftLastWriteTime;
else
ft.dwLowDateTime = ft.dwHighDateTime = 0;
}
FILETIME lastwrite;
getLastWriteTime_as_FILETIME(entry.path(), lastwrite);