Skip to content

SetCreationTime on Mac #39132

@hamarb123

Description

@hamarb123

Description

The method System.IO.File.SetCreationTime[Utc](string, DateTime) does not work correctly on mac, but the System.IO.File.GetCreationTime[Utc](string, DateTime) does.
The following code snippet creates different results on mac and windows:

using System.IO;

static class Program
{
  static void Main()
  {
    string filePath = @"/path/to/file"; //change to appropriate path where file doesn't exist
    File.Create(filePath);
    FileInfo fi = new FileInfo(filePath);
    fi.LastAccessTimeUtc = new DateTime(2020, 1, 2);
    fi.LastWriteTimeUtc = new DateTime(2020, 1, 3);
    fi.CreationTimeUtc = new DateTime(2020, 1, 1);
    fi.Refresh();
    Console.WriteLine(fi.LastAccessTimeUtc.ToString()); //expect 2/1/2020 12:00:00 am
    Console.WriteLine(fi.LastWriteTimeUtc.ToString()); //expect 3/1/2020 12:00:00 am, get 1/1/2020 12:00:00 am on Mac
    Console.WriteLine(fi.CreationTimeUtc.ToString()); //expect 1/1/2020 12:00:00 am
  }
}

I believe that this method contains the implementation for Unix platforms, but I think that Mac should have a different implementation for this function to Unix as there is an actual way to do this on Mac.

Swift code to change date:

let filePath = "/path/to/file"
let date = NSDate()
let fileAttributes = [FileAttributeKey.creationDate: date]
FileManager.default.setAttributes(fileAttributes, ofItemAtPath: filePath)

This code, in theory, sets the creation date of the file; there must be a way to implement this in C# on the Mac version, it is also probably a good idea to implement the other methods (last write and access dates) like this, as it seems that setting the last write date changes the creation date sometimes (see this).

Configuration

I tested the code on macOS Catalina (x64) and Windows 10 (x64). It is specific to unix platforms.

Regression?

I do not know.

Other information

A workaround could be to set the creation date, and then set the modification date back again. This will work sometimes, but not always.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions