【发布时间】:2013-08-20 15:54:13
【问题描述】:
我需要获取文件的创建时间 - 我尝试过使用:
FileInfo fi = new FileInfo(FilePath);
var creationTime = fi.CreationTimeUtc;
和
var creationTime = File.GetCreationTimeUtc(FilePath);
这两种方法通常都返回错误的创建时间 - 我猜它被缓存在某个地方。
该文件被删除并以相同的名称重新创建,我需要知道它何时/是否被重新创建(通过检查创建的日期/时间是否已更改) - 我计划通过查看来执行此操作文件创建时间已更改,但我发现这不准确。
我正在使用 Win 7,如果我检查文件资源管理器,它会正确显示新文件的创建时间。
我也尝试过使用 FileSystemWatcher,但它并不完全适用于我的用例。例如。如果我的程序没有运行,则 FileSystemWatcher 没有运行,所以当我的程序再次启动时,我不知道文件是否已被删除并重新创建。
我看过 MSDN http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime.aspx 上面写着:
此方法可能返回不准确的值,因为它使用的本机函数的值可能不会被操作系统持续更新。
但我也尝试使用他们的替代建议并在创建新文件后设置 SetCreationDate 但我也发现这不起作用。请参阅下面的测试:
[Test]
public void FileDateTimeCreatedTest()
{
var binPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
var fullFilePath = Path.Combine(binPath, "Resources", "FileCreatedDatetimeTest.txt");
var fullFilePathUri = new Uri(fullFilePath);
var dateFormatted = "2013-08-17T15:31:29.0000000Z"; // this is a UTC string
DateTime expectedResult = DateTime.MinValue;
if (DateTime.TryParseExact(dateFormatted, "o", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out expectedResult)) // we expect the saved datetime to be in UTC.
{
}
File.Create(fullFilePathUri.LocalPath);
Thread.Sleep(1000); // give the file creation a chance to release any lock
File.SetCreationTimeUtc(fullFilePathUri.LocalPath, expectedResult); // physically check what time this puts on the file. It should get the local time 16:31:29 local
Thread.Sleep(2000);
var actualUtcTimeFromFile = File.GetCreationTimeUtc(fullFilePathUri.LocalPath);
Assert.AreEqual(expectedResult.ToUniversalTime(), actualUtcTimeFromFile.ToUniversalTime());
// clean up
if (File.Exists(fullFilePathUri.LocalPath))
File.Delete(fullFilePathUri.LocalPath);
}
非常感谢任何帮助。
【问题讨论】:
-
您是否尝试过使用
FileInfo.Refresh? -
成功了 - 谢谢!