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.