C#中的文件创建时间

Wil*_*ill 11 .net c# .net-4.5

我需要在创建文件时获取 - 我尝试过使用:

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)

任何帮助非常感谢.

Yuc*_*uck 9

你需要使用Refresh:

FileSystemInfo.Refresh从当前文件系统获取文件的快照.即使文件系统返回不正确或过时的信息,刷新也无法更正基础文件系统.这可能发生在Windows 98等平台上.

在尝试获取属性信息之前必须调用Refresh,否则信息将过时.

来自MSDN的关键位表明它需要一个快照属性信息......将会过时.