c# Get File Last Access or Usuability

1.8k Views Asked by At

I need to inspect all files within a Repository periodically and compare its LastAccessTime in order to know when was the last time that file was used (accessed, modified and/or updated).

I've already been tried with File.GetLastAccessTime() and FileInfo.LastAccessTime, but I always get the same DateTime after open/close it, or read it.

How could I know when a file has been used?

Thanks!

string path = System.Environment.CurrentDirectory + "/testing/doc2.txt"
Console.WriteLine("--------------------------------------");
Console.WriteLine("GetLastAccessTime {0}", File.GetLastAccessTime(path));
Console.WriteLine("GetLastAccessTimeUtc {0}", File.GetLastAccessTimeUtc(path));
Console.WriteLine("Directory.GetLastAccessTime {0}", Directory.GetLastAccessTime(path));
FileInfo fi = new FileInfo(path);
Console.WriteLine("fi.LastAccessTime {0}", fi.LastAccessTime);

output:

GetLastAccessTime           12/18/2018 11:41:15 AM
GetLastAccessTimeUtc        12/18/2018 4:41:15 PM
Directory.GetLastAccessTime 12/18/2018 11:41:15 AM
fi.LastAccessTime           12/18/2018 11:41:15 AM
--------------------------------------
GetLastAccessTime           12/18/2018 11:41:15 AM
GetLastAccessTimeUtc        12/18/2018 4:41:15 PM
Directory.GetLastAccessTime 12/18/2018 11:41:15 AM
fi.LastAccessTime           12/18/2018 11:41:15 AM
1

There are 1 best solutions below

0
On

The most important thing is, what file system you are using. I suppose it is NTFS. Then there a few quotations:

Last access timestamp of a file is the last date and time when that file was opened for reading or writing. So every time a user access a file this timestamp needs to be updated, which is a bit of an overhead especially if you are not too keen on this file attribute. To improve the performance of NTFS filesystem in Windows 10 (and previous versions starting from Windows Vista) the last access times of files and directories are NOT updated.

Source here

Bonus chatter: Starting in Windows Vista, maintaining the last-access time is disabled by default. In practice, this means that the number of bugs related to altering the last-access time accidentally will multiply unchecked, because the mechanism for detecting the error is disabled by default.

Source here

And one more link, where it seems like there is still another behaviour.

And last link for FAT. I'm not so sure, since I last read only the FAT12 (floppy drive/diskettes) description many, many rears ago, but there probably is not a space to store last access time in FAT file systems, only the date is stored. I can not confirm this for the extension Microsoft provided with long file names.