C#中的文件创建时间

时间:2013-08-20 15:54:14

标签: c# .net .net-4.5

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

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);
    }

任何帮助都非常感激。

4 个答案:

答案 0 :(得分:9)

您需要使用Refresh

  

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

     

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

来自MSDN的关键位表示它拍摄快照属性信息......将会过时

答案 1 :(得分:3)

尝试使用FileInfoRefresh方法

fileInfo.Refresh();
var created = fileInfo.CreationTime;

这应该有效

答案 2 :(得分:0)

 File.Create(fullFilePathUri.LocalPath);
 Thread.Sleep(1000); // give the file creation a chance to release any lock

这不是你怎么做的。 File.Create创建流编写器,应该关闭它以释放锁而无需等待。如果你发现自己使用Thread.Sleep,你会经常发现你做错了。

答案 3 :(得分:-1)

如果path参数中描述的文件不存在,则此方法将返回公元1601年1月1日午夜12:00(协调世界时),已调整为本地时间。

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.getcreationtime?view=netframework-4.8