如何在不影响“上次写入时间”的情况下更改文件

时间:2013-04-09 13:59:38

标签: c# file-io timestamp filesystemwatcher

我想写一些文件,比如

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

但是,这会更改"last write time"。我可以稍后使用

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

但与此同时,FileSystemWatcher已触发。

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

2 个答案:

答案 0 :(得分:4)

您可以通过在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

答案 1 :(得分:2)

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

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

只需创建一个标志:boolean,如果你这样写并注意到同一个应用程序, 或flag,如某些特定的命名文件,如果你写一个表格并从另一个应用程序观看。