Question

After moving a file to another location, and then creating a file with the same name in the original location, the creation time is incorrect

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?

 2  40  2
1 Jan 1970

Solution

 6

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").

2024-07-25
wohlstad