我需要在创建文件时获取 - 我尝试过使用:
FileInfo fi = new FileInfo(FilePath);
var creationTime = fi.CreationTimeUtc;
Run Code Online (Sandbox Code Playgroud)
和
var creationTime = File.GetCreationTimeUtc(FilePath);
Run Code Online (Sandbox Code Playgroud)
这两种方法通常都会返回错误的创建时间 - 我猜它正在某处缓存.
该文件被删除并使用相同的名称重新创建,我需要知道何时/是否已重新创建(通过检查创建的日期/时间是否已更改) - 我计划通过查看文件来执行此操作创作时间已经改变,但我发现这是不准确的.
我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助非常感谢.