.NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong

Mr. Flibble picture Mr. Flibble · Sep 19, 2009 · Viewed 22.9k times · Source

When I call FileInfo(path).LastAccessTime or FileInfo(path).LastWriteTime on a file that is in the process of being written it returns the time that the file was created, not the last time it was written to (ie. now).

Is there a way to get this information?

Edit: To all the responses so far. I hadn't tried Refresh() but that does not do it either. I am returned the time that the file was started to be written to. The same goes for the static method, and creating a new instance of FileInfo.

Codymanix might have the answer, but I'm not running Windows Server (using Windows 7), and I don't know where the setting is to test.

Edit 2: Nobody finds it interesting that this function doesn't seem to work?

Answer

Tommy Carlier picture Tommy Carlier · Sep 19, 2009

The FileInfo values are only loaded once and then cached. To get the current value, call Refresh() before getting a property:

f.Refresh();
t = f.LastAccessTime;

Another way to get the current value is by using the static methods on the File class:

t = File.GetLastAccessTime(path);