c# - 如何从很长的路径获取文件的创建日期时间?

标签 c# datetime kernel32 interopservices safehandle

我的文件路径很长,所以只能使用 SafeFileHandle 来处理。
想要获取创建日期时间。
当尝试获取 millies 然后在 DateTime 中转换时,它会减少 1600 年。

代码:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetFileTime(SafeFileHandle hFile, ref long lpCreationTime, ref long lpLastAccessTime, ref long lpLastWriteTime);

void fnc(String file){
    var filePath = @"\\?\" + file;
    var fileObj = CreateFile(filePath, Constants.SafeFile.GENERIC_READ, 0, IntPtr.Zero, Constants.SafeFile.OPEN_EXISTING, 0, IntPtr.Zero);
    long millies = 0, l1 = 0, l2 = 0;

    if(GetFileTime(fileObj, ref millies, ref l1, ref l2))
    {
        DateTime creationTime = new DateTime(millies, DateTimeKind.Local);

高于 creationTime 少了 1600 年。它不是 2019 年,而是 0419。

然后我不得不这样做

        DateTime creationTime = new DateTime(millies, DateTimeKind.Local).AddYears(1600);
    }
}

上面的 creationTime 是正确的,因为我添加了 1600 年。

是什么让日期少了 1600 年?
我做错了什么吗?

最佳答案

这完全是在处理文件时间时设计的。

返回文件时间的基础是 01/01/1601 的计数器:

A file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 A.M. January 1, 1601 Coordinated Universal Time (UTC).

引用 official documentation .

关于c# - 如何从很长的路径获取文件的创建日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289053/

相关文章:

javascript - 如果月份无效,如何从 DOB 计算年龄?

python-2.7 - 如何以 Day, Date Month Year HH :MM:SS? 格式打印当前时间

vb.net - PInvoke FormatMessage Message ByRef lpBuffer As [String] 没有

C# GetProcAddress 返回零

visual-c++ - 错误无法打开文件 'kernel32.lib'

c# - 使用 .Net 4.0 时出现 PInvoke StackImbalance 错误,但使用 .Net 2.0 时则不会

c# - 在 C# 中关闭/处理 ServiceHost 线程的正确方法?

sql - sql server中日期时间的内部表示是什么?

c# - WPF C# 以编程方式添加事件处理程序

c# - DataGridView更改单元格背景并恢复默认样式