StreamWriter 打开时修改日期未更新 [英] Date Modified isn't updated while StreamWriter is open

查看:28
本文介绍了StreamWriter 打开时修改日期未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志记录解决方案并写入一个在应用程序运行时打开的文本文件.我使用 StreamWriter 写入文件.我的记录器代码很简单(打开流和写入):

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:我使用的是 Windows 7

PS: I am on Windows 7

推荐答案

FindNextFile 返回的修改日期是存储在目录项中的缓存值,而不是存储在 MFT 记录中的始终更新的值(inode 等效).这是出于性能原因,因此可以通过一次读取获得整个目录的信息,而不是读取每个文件.

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.*

您始终可以通过使用 GetFileInformationByHandleGetFileInformationByHandleEx 获取最新信息.要使用此功能,您应该使用 CreateFile 打开文件,同时不请求读写权限并允许共享.

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);

此句柄可以与 GetFileInformationByHandleEx 一起使用.

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.)

这篇关于StreamWriter 打开时修改日期未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆