文件的CreationDate正在根据上下文进行更改

时间:2012-01-27 15:38:06

标签: c# file-io

我在文件的创建日期运行一些基本的单元测试,我在一个奇怪的情况下运行(至少对我来说):

    [TestInitialize]
    public void Initialize()
    {
        if (File.Exists(UncFile))
            File.Delete(UncFile);
        if (File.Exists(LocalFile))
            File.Delete(LocalFile);
    }

    [TestMethod]
    public void ProxyFile_DeleteOlderFileOnLocalSystem()
    {
        using (StreamWriter sw = File.CreateText(LocalFile)) { }
        Thread.Sleep(50);

        using (StreamWriter sw = File.CreateText(UncFile)) { }
        Thread.Sleep(50);

        DateTime UncDate = File.GetCreationTime(UncFile);
        DateTime OldLocalDate = File.GetCreationTime(LocalFile);

        Assert.IsTrue(UncDate > OldLocalDate);
    }

工作正常!而:

    [TestInitialize]
    public void Initialize()
    {
        using (StreamWriter sw = File.CreateText(UncFile)) { }

        if (File.Exists(UncFile))
            File.Delete(UncFile);
        if (File.Exists(LocalFile))
            File.Delete(LocalFile);
    }


    [TestMethod]
    public void ProxyFile_DeleteOlderFileOnLocalSystem()
    {
        using (StreamWriter sw = File.CreateText(LocalFile)) { }
        Thread.Sleep(50);

        using (StreamWriter sw = File.CreateText(UncFile)) { }
        Thread.Sleep(50);

        DateTime UncDate = File.GetCreationTime(UncFile);
        DateTime OldLocalDate = File.GetCreationTime(LocalFile);

        Assert.IsTrue(UncDate > OldLocalDate);
    }

让我虚假......两者之间唯一不同的是:

using (StreamWriter sw = File.CreateText(UncFile)) { }

但我删除了这个文件:

if (File.Exists(UncFile))
                File.Delete(UncFile);

有人能指出我做的不对吗?

THX。

[编辑]

第二个示例中的日期似乎与第一个文件UNC Created:

相似
Debug.Print("UncFile : " + File.GetCreationTime(UncFile).Ticks);
->
UncFile   (Init) : 634632802355468953
UncFile   (Test) : 634632802355468953
LocalFile (Test) : 634632802355618962

[/编辑]

1 个答案:

答案 0 :(得分:1)

确定找到了:

  

File.GetCreationTime Method

     
    

注意此方法可能会返回一个不准确的值,因为它使用了     本机函数的值可能不会被连续更新     操作系统。

  

感谢raymond链接到Stackoverflow中的另一个答案,以下是解决方案:

 using (StreamWriter sw = File.CreateText(LocalFile)) { }
            File.SetCreationTime(LocalFile,DateTime.Now);
            Thread.Sleep(50);

            using (StreamWriter sw = File.CreateText(UncFile)) { }
            File.SetCreationTime(UncFile, DateTime.Now);
            Thread.Sleep(50);

            DateTime UncDate = File.GetCreationTime(UncFile);
            DateTime OldLocalDate = File.GetCreationTime(LocalFile);

            Assert.IsTrue(UncDate > OldLocalDate);