【问题标题】:How to change a file without affecting the "last write time"如何在不影响“最后写入时间”的情况下更改文件
【发布时间】:2013-04-09 13:59:37
【问题描述】:

我想写一些东西到文件中,比如

using( var fs = File.OpenWrite( file ) )
{
  fs.Write( bytes, 0, bytes.Length );
}

但是,这会更改 "last write time"。我可以稍后重置它,通过使用

File.SetLastWriteTime( file, <old last write time> );

但与此同时,FileSystemWatcher 已经触发。

现在我的问题是:是否可以在不改变“最后写入时间”的情况下写入文件?

【问题讨论】:

  • 你真的真的真的很想要那个吗?您确实确实写入了文件。相反,您可以暂停 FileSystemWatcher(这已经不可靠),因此您不必弄乱虚假的写入时间。
  • 我不这么认为!除非您更换底层驱动程序 :P :) !
  • @JustAnotherUserYouMayKnow:FileSystemWatcher 不一定在我的控制之下:/

标签: c# file-io timestamp filesystemwatcher


【解决方案1】:

您可以通过在 Kernel32.dll 中使用 P/Invoke 调用来实现。

来自 MS TechNet 的This Powershell script 实现了这一点,并明确声明不会触发FileSystemWatcher 的事件。

我已经简要查看了脚本,代码非常简单,可以轻松复制到您的 C# 项目中。

声明:

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetFileTime(IntPtr hFile, ref long lpCreationTime, ref long lpLastAccessTime, ref long lpLastWriteTime);

脚本在写入前使用SetFileTime锁定文件时间。

private const int64 fileTimeUnchanged = 0xFFFFFFFF;

这个常量作为对 lpCreationTime、lpLastAccessTime 和 lpLastWriteTime 方法的引用传递:

// assuming fileStreamHandle is an IntPtr with the handle of the opened filestream
SetFileTime(fileStreamHandle, ref fileTimeUnchanged, ref fileTimeUnchanged, ref fileTimeUnchanged);
// Write to the file and close the stream

【讨论】:

  • 感谢您的建议。这似乎是一个可能的解决方案,不幸的是直到现在,我无法让它工作。一旦我知道更多,我会提供一些反馈。
【解决方案2】:

不认为这是可能的,我也不知道。

还要考虑“最后写入时间” Is Not Always Updated,如果您要根据该参数从文件夹中选择(例如)一些文件或以某种方式依赖该属性,这会导致一些有线结果。因此,它不是您在开发中可以依赖的参数,只是操作系统架构不可靠。

只需创建一个标志:boolean,如果您在同一个应用程序中编写并监视它, 或flag,比如某个特定的命名文件,如果您编写表单并从另一个应用程序观看。

【讨论】:

  • 感谢您的回答。我无法使用标志或文件,因为带有 FileSystemWatcher 的应用程序不在我的控制之下。
猜你喜欢
  • 2019-01-27
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2012-03-04
相关资源
最近更新 更多