Search code examples
c#concurrencyfileinfo

C# FileInfo and concurrent modification?


It's a simple question most likely, but I couldn't find the proper answer:

If I create a FileInfo-Object and access it's properties during long-running code - is it cached (i.e. a snapshot of the time I created the FileInfo-Object) or are some Properties evaluated when accessed? (Or even mixed?)

i.e.:

FileInfo fi = new FileInfo("C:\myfile.txt"); //Time A

//Do something. Another Process will now edit the file, and save it,
//while this code is running. Let's call this Time B 

Log(fi.LastWriteTime.ToString());

Will I log Time A or Time B?

(Same question ofc. applies for filesize and other attributes)

ps.: I know I could just test it for the write time, but since there are a lot of attributes, I don't want to test them all.


Solution

  • FileInfo caches the file attribute info, like length, exist etc. This state is loaded on the first access to any of these properties. There is a Refresh() method that reloads all file attributes for the FileInfo.

    This can be seen by examining the implementation of fileInfo