文件的创建日期根据上下文而变化
本文关键字:上下文 变化 创建日期 文件 | 更新日期: 2023-09-27 18:21:32
我在文件创建日期运行一些基本的单元测试,我在一个奇怪的情况下运行(至少对我来说):
[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);
}
gaves me false。。。两者之间唯一的区别是:
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
[/EDIT]
OK找到它:
File.GetCreationTime方法
注意此方法可能返回不准确的值,因为它使用其值可能不会由操作系统。
感谢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);