问题
I have a logging solution and write to a textfile which is open when aplication is running. I use StreamWriter to write to file. My logger code is simply (to open stream and to write):
public void Open(string filePath, bool append)
{
if (this.logWriter != null)
throw new InvalidOperationException(
"Logger is already open");
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
this.logWriter = new StreamWriter(filePath, append);
this.logWriter.AutoFlush = true;
}
public void CreateEntry(string entry)
{
if (this.logWriter == null)
return;
this.logWriter.WriteLine(entry);
}
Problem is that while writing to file, entries are written, file size is changing, but "Date Modified" attribute doesn't change. Any thoughts? How can I manually update modify date?
PS: I am on Windows 7
回答1:
The modified date returned by FindNextFile
is the cached value stored in the directory entry, not the always updated value stored in the MFT record (inode equivalent). This is for performance reasons, so the information for a whole directory can be obtained with a single read, rather than a read for each file.
It is updated whenever an handle to the file is closed.*
You can always get up-to-date information by using GetFileInformationByHandle
or GetFileInformationByHandleEx
. To use this function you should open the file using CreateFile
, while requesting neither read nor write access and allowing sharing.
HANDLE hFile = CreateFile(_T("Path/To/File"),
0, // No read or write access needed
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING, // Don't create
0, NULL);
This handle can then be used with GetFileInformationByHandleEx
.
Alternatively simply closing this handle will update the directory entry to reflect the current values.
*(To be accurate, whenever a handle which was opened through that name is closed, since a file can have multiple hard links.)
来源:https://stackoverflow.com/questions/36219705/date-modified-isnt-updated-while-streamwriter-is-open