My code:
//Move the file to another location
File.Move(@"D:\Test.log", @"D:\LogHistory\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".log");
//Create the file with the same name again in the original location,the time the file was created is not the time the code was executed.
StreamWriter _writer = new StreamWriter(@"D:\Test.log", true);
_writer.Close();
As shown above, I want to move a log file to a history folder and then create another log file with the same name in the same location, but the new log file is created at a time other than the current time.
Can anyone explain why? Is this phenomenon related to the file system?
Windows "remembers" that there was a file named @"D:\Test.log"
before it was moved.
When you create a new file with the same name, the creation time is taken from the original file.
This is a feature called file tunneling, and according to this answer in a Microsoft forum by a moderator it is the expected behavior.
There is also this article that explains it in more details: The apocryphal history of file system tunnelling.
Note that the "last modified" time does change as expected.
My recommendation is not to rely on the creation time maintained by the OS.
One solution commonly used by logging frameworks is to embed the actual creation time in the file name (e.g. "Log_2024_07_25__11_11_11.log"
).