C# GetLastWriteTime返回1600年12月31日下午7:00:00

C# GetLastWriteTime返回1600年12月31日下午7:00:00,c#,directory,.net-3.5,label,C#,Directory,.net 3.5,Label,我使用以下代码将目录的日期修改时间写入标签 string selectedPath = comboBox1.SelectedItem.ToString(); DateTime lastdate = Directory.GetLastWriteTime(selectedPath); datemodified.Text = lastdate.ToString(); 它返回的日期是1600年12月31日下午7:00:00,我不知道它是从哪里得到这个日期的。有人能帮我理解为什么它会返回那个日期,以及我

我使用以下代码将目录的日期修改时间写入标签

string selectedPath = comboBox1.SelectedItem.ToString();
DateTime lastdate = Directory.GetLastWriteTime(selectedPath);
datemodified.Text = lastdate.ToString();
它返回的日期是1600年12月31日下午7:00:00,我不知道它是从哪里得到这个日期的。有人能帮我理解为什么它会返回那个日期,以及我如何修复它吗?我使用的.NET 3.5来自:

如果path参数中描述的目录不存在,则此方法返回公元1601年1月1日午夜12:00(C.E.)协调世界时(UTC),调整为本地时间


因此,假设您的时区是UTC-5(1月),而目录不存在…

首先想到的是您的时间设置是否正确。第二个想法是右键单击该文件夹并查看它在属性中的内容。最后,我将创建一个新的测试文件夹,并在其上运行GetLastWriteTime测试,这样您就可以知道返回的内容。

GetLastWriteTime
并非总是返回可靠的日期时间,请使用此选项

string selectedPath = comboBox1.SelectedItem.ToString();
DateTime now = DateTime.Now;
TimeSpan localOffset = now - now.ToUniversalTime();
DateTime lastdate = File.GetLastWriteTimeUtc(selectedPath) + localOffset;
datemodified.Text = lastdate.ToString();

老问题,但今天我面对这个问题。当路径无效或文件不存在时,也会返回该特定日期,因为在这些情况下都没有内置异常。

一种测试文件未找到的简便方法,其结果为
GetLastWriteTime()
/
GetLastWriteTimeUtc()
在不硬编码的情况下,用于指示文件/dir未找到状态的sentinel历元日期/时间如下:

// ##### Local file time version #####
DateTime fileTimeEpochLocal=DateTime.FromFileTime(0);
// Use File.GetLastWriteTime(pathname) for files
// and Directory.GetLastWriteTime(pathname) for directories
DateTime lastWriteTime=Directory.GetLastWriteTime(selectedPath); 

// Check for a valid last write time
if (lastWriteTime!=fileTimeEpochLocal) // File found
    DoSomethingWith(selectedPath,lastWriteTime);
else // File not found
    HandleFileNotFound(selectedPath);

// ##### UTC file time version #####
DateTime fileTimeEpochUtc=DateTime.FromFileTimeUtc(0);
// Use File.GetLastWriteTimeUtc(pathname) for files
// and Directory.GetLastWriteTimeUtc(pathname) for directories
DateTime lastWriteTimeUtc=Directory.GetLastWriteTimeUtc(selectedPath);

// Check for a valid last write time
if (lastWriteTimeUtc!=fileTimeEpochUtc) // File found
    DoSomethingWith(selectedPath,lastWriteTimeUtc);
else // File not found
    HandleFileNotFound(selectedPath);

在.NETCore中,需要获取文件的绝对路径。 添加对Microsoft.Extensions.Hosting的引用,并将其注入构造函数中。
ContentRootPath
属性将是您的web根目录

获取您的服务器路径

var Files=FIO.Directory.GetFiles(“解压缩”);
这将是您的实际路径

var Path=string.Format(@{0}\{1}),WebRootPath,文件[0]);
var CreationDate=File.GetLastWriteTime(路径);

只要告诉我Jon你在哪里记得这些?@NikhilAgrawal在msdn上查找调用的定义即可。一个人不需要记住所有的事情,只需要记住我们要看的那个日期是否有任何意义(除了参数不存在之外)?@Snoop:这可能只是碰巧选择的一个纪元。在整个计算过程中,有很多时代在使用——1582年用于GUID时间戳,1AD用于.NET,1970-01-01年用于任何基于Unix的系统,1900年用于Excel IIRC…@JonSkeet Ok。我已经有一段时间没用Java了,但我知道他们以前有一个。。。就像“当Java被发明的时候”之类的。。。我想知道微软选择这个日期是否有历史意义。周一,‎也许‎07, ‎2012, ‏‎下午4:06:00是其中一个文件夹上的日期。这对我来说很奇怪。代码是有意义的,但是它返回的内容是没有意义的