Reputation: 2293
I am running some basic unit test on the creation date of files and I runned in a strange case (to me at least):
[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);
}
Works fine! whereas :
[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... The Only Difference between the two being :
using (StreamWriter sw = File.CreateText(UncFile)) { }
But I delete this file just after :
if (File.Exists(UncFile))
File.Delete(UncFile);
Could someone point me out what I am not doing right?
thx.
[EDIT]
the date in the second example seems to be like the first file UNC Created :
Debug.Print("UncFile : " + File.GetCreationTime(UncFile).Ticks);
->
UncFile (Init) : 634632802355468953
UncFile (Test) : 634632802355468953
LocalFile (Test) : 634632802355618962
[/EDIT]
Upvotes: 1
Views: 427
Reputation: 2293
OK found it :
Note This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by the operating system.
Thanks to raymond link's to another answer in Stackoverflow , Here is the solution :
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);
Upvotes: 1