Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong

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?

like image 313
Mr. Flibble Avatar asked Sep 19 '09 15:09

Mr. Flibble


People also ask

What is LastWriteTime in C#?

Description. FileInfo LastWriteTime Gets or sets the time when the current file or directory was last written to.

What does LastWriteTime mean?

LastWriteTime. The time the file was last written to. ChangeTime. The time the file was changed.

What is LastAccessTime?

lastaccesstime: Gets or sets the time the current file or directory was last accessed.

How do I get LastWriteTime in PowerShell?

Use the Get-ChildItem LastWriteTime attribute to find the list of files with lastwritetime. Get-ChildItem in the PowerShell gets one or more child items from the directory and subdirectories.


2 Answers

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); 
like image 137
Tommy Carlier Avatar answered Sep 26 '22 04:09

Tommy Carlier


Starting in Windows Vista, last access time is not updated by default. This is to improve file system performance. You can find details here:

http://blogs.technet.com/b/filecab/archive/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance.aspx

To reenable last access time on the computer, you can run the following command:

fsutil behavior set disablelastaccess 0

like image 23
James Kovacs Avatar answered Sep 22 '22 04:09

James Kovacs