Changing the file creation date does not work

Actually, each file has three different times:

  1. Creation time
  2. Last access time
  3. Last write time (that's shown in Explorer and other file managers as "File Date")

To modify these times you can use

File.SetCreationTime(path, time);
File.SetLastWriteTime(path, time);
File.SetLastAccessTime(path, time);

respectively.

It seems, that if you want to change file date as it shown in file manager (e.g. Explorer) you should try something like that:

String path = @"changemydate.txt";                
DateTime time = new DateTime(year, month, day, hour, minutes, seconds); 

if (File.Exists(path))
    File.SetLastWriteTime(path, time);

I had some trouble with this. This was my code:

    FileInfo fileInfo = new FileInfo(path);

    // do stuff that adds something to the file here

    File.SetAttributes(path, fileInfo.Attributes);
    File.SetLastWriteTime(path, fileInfo.LastWriteTime);

Looks good, does it not? Well, it does not work.

This does work though:

    FileInfo fileInfo = new FileInfo(path);

    // note: We must buffer the current file properties because fileInfo
    //       is transparent and will report the current data!
    FileAttributes attributes = fileInfo.Attributes;
    DateTime lastWriteTime = fileInfo.LastWriteTime;

    // do stuff that adds something to the file here

    File.SetAttributes(path, attributes);
    File.SetLastWriteTime(path, lastWriteTime);

And Visual Studio does not help. If you break on the line that resets the time, the debugger will report the original value you want to write back. So this looks good and leads you to believe you are injecting the right date. It seems VS is not aware of the transparency of the FileInfo object and is reporting cached values.

The documentation for FileInfo states:

When the properties are first retrieved, FileInfo calls the Refresh method and caches information about the file. On subsequent calls, you must call Refresh to get the latest copy of the information.

Well... not quite, apparently. It appears to refresh on its own.


You can use this code sample

string fileName = @"C:\MyPath\MyFile.txt"; 
if (File.Exists(fileName)) 
{       
    DateTime fileTime = DateTime.Now; 
    File.SetCreationTime(fileName, fileTime);         
}

Tags:

C#

Datetime

File