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

C# 如何从很长的路径中获取文件的创建日期时间?,c#,datetime,kernel32,interopservices,safehandle,C#,Datetime,Kernel32,Interopservices,Safehandle,我有很长的文件路径,因此只能使用SafeFileHandle处理 要获取创建日期时间。 如果尝试获取毫秒,然后在DateTime中进行转换,则会少1600年 代码: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwSha

我有很长的文件路径,因此只能使用
SafeFileHandle
处理
要获取创建日期时间。
如果尝试获取毫秒,然后在
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年?

我做错了什么吗?

在处理文件时间时,这完全是出于设计

返回文件时间的依据是1601年1月1日的计数器:

文件时间是一个64位的值,表示 自1月1日凌晨12:00起,间隔为100纳秒, 1601协调世界时(UTC)


参考。

GetFileTime返回的FILETIME结构返回从1601年1月1日开始的100纳秒间隔数。您可以在此处查看相关文档:

有一个内置的.net函数可以为您转换-
DateTime.FromFileTime()
,而不是增加1600年。在您的示例中,代码是:

if(GetFileTime(fileObj,ref milies,ref l1,ref l2))
{
DateTime creationTime=DateTime.FromFileTime(毫秒);
}

我还想将变量名从
milies
更改,因为这有点误导(GetFileTime不返回毫秒)。

GetFileTime返回的FILETIME结构返回从1601年1月1日开始的100纳秒间隔数:我相信您可以使用DateTime.FromFileTime()安全地转换感谢@Martin。所以我想在我的例子中加上1600年才是正确的,对吧?谢谢@theduck,即使我被名字
milies
弄糊涂了,我也可以把它改成类似于
滴答声
。还有其他建议吗?我想这取决于你的命名惯例,但CreationTimeticks?这很有意义!