Incredible file creation time issue

I have a very strange problem! I wonder if there is a problem within the OS, or maybe it's just me, a misunderstanding of things ...

I have a file that can be created long ago, I use this file, and then I want to archive it by changing its name. Then I want to create a new file with the same name as the old file, before renaming it. Easy enough!

The problem that really puzzles me is that the newly created file mistakenly "created" -timestamp! This is a problem because it is a timestamp that I want to use to determine when to archive and create a new file.

I created a very small sample that shows the problem. For the sample to work, the 1.txt file must be in the Files folder. In addition, the file attribute must also be set in time (with one of the tools available, I use Nomad.NET).

static void Main(string[] args) { // Create a directory, if doesnt exist. string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\Files"; Directory.CreateDirectory(path); // Create/attach to the 1.txt file string filename = path + "\\1.txt"; StreamWriter sw = File.AppendText(filename); sw.WriteLine("testing"); sw.Flush(); sw.Close(); // Rename it... File.Move(filename, path + "\\2.txt"); // Create a new 1.txt sw = File.AppendText(filename); FileInfo fi = new FileInfo(filename); // Observe, the old files creation date!! Console.WriteLine(String.Format("Date: {0}", fi.CreationTime.Date)); Console.ReadKey(); } 
+24
c # windows filesystems
Jan 21 '10 at 12:35 on
source share
3 answers

This is the result of a secret "function" going back to the old days of Windows. Basic information here:

In principle, this is on purpose. But it is customizable and an anachronism in most modern programs.

I think you can create a new file name first, and then rename old-> old.1, then new-> old, and it will work. I honestly do not remember what we did when we encountered this last several years ago.

+28
Jan 21 '10 at 12:57
source share

I recently ran into the same issue as in the question. In our case, if our log file is older than a week, we will delete it and run a new one. However, he kept the same date as from 2008.

One answer here describes renaming an old file, and then creating a new one, hoping to get the correct creation date. However, for us this was not successful, he retained the old date.

We used the File.SetCreationTime method, and as its name suggests, it easily allows us to control the date the file was created, allowing us to set it to DateTime.Now. After that, the rest of our logic worked correctly.

+9
Jun 13 2018-11-11T00:
source share

File.SetCreationTime ("file", DateTime.Now);

+2
Mar 13 '13 at 20:53
source share



All Articles