22

我正在使用以下内容来更改文本文件的创建日期:

using System.IO;

...
DateTime newCreate = new DateTime(year, month, day, hour, minutes, seconds);
File.SetCreationTime("changemydate.txt", newCreate);

然而,这并没有做任何事情。没有错误消息,但它根本不会更改文件的日期。

我在保管箱文件夹以及随机文件夹中尝试了这个但没有成功

DateTime newCreate对象似乎是正确的。

如果有人能指出我的想法,那就太好了...

4

6 回答 6

34

实际上,每个文件都有三个不同的时间

  1. 创建时间
  2. 上次访问时间
  3. 上次写入时间(在资源管理器和其他文件管理器中显示为“文件日期”)

要修改这些时间,您可以使用

File.SetCreationTime(path, time);
File.SetLastWriteTime(path, time);
File.SetLastAccessTime(path, time);

分别。

看来,如果您想更改文件管理器(例如资源管理器)中显示的文件日期,您应该尝试以下操作:

String path = @"changemydate.txt";                
DateTime time = new DateTime(year, month, day, hour, minutes, seconds); 

if (File.Exists(path))
    File.SetLastWriteTime(path, time);
于 2013-06-15T17:16:21.253 回答
3

我遇到了一些麻烦。这是我的代码:

    FileInfo fileInfo = new FileInfo(path);

    // do stuff that adds something to the file here

    File.SetAttributes(path, fileInfo.Attributes);
    File.SetLastWriteTime(path, fileInfo.LastWriteTime);

看起来不错,不是吗?好吧,它不起作用。

这确实有效:

    FileInfo fileInfo = new FileInfo(path);

    // note: We must buffer the current file properties because fileInfo
    //       is transparent and will report the current data!
    FileAttributes attributes = fileInfo.Attributes;
    DateTime lastWriteTime = fileInfo.LastWriteTime;

    // do stuff that adds something to the file here

    File.SetAttributes(path, attributes);
    File.SetLastWriteTime(path, lastWriteTime);

而 Visual Studio 也无济于事。如果您在重置时间的行上中断,调试器将报告您要写回的原始值。所以这看起来不错,让你相信你注射了正确的日期。似乎 VS 不知道 FileInfo 对象的透明度并且正在报告缓存值。

FileInfo 的文档指出:

首次检索属性时,FileInfo 调用 Refresh 方法并缓存有关文件的信息。在后续调用中,您必须调用 Refresh 以获取信息的最新副本。

嗯……不完全是,显然。它似乎会自行刷新。

于 2020-07-06T10:32:18.220 回答
1

您可以使用此代码示例

string fileName = @"C:\MyPath\MyFile.txt"; 
if (File.Exists(fileName)) 
{       
    DateTime fileTime = DateTime.Now; 
    File.SetCreationTime(fileName, fileTime);         
}
于 2013-06-15T16:59:33.917 回答
1

我从来没有遇到过 SetCreationTime 的问题……但我认为你可以通过 getter/setter CreationTime 在 FileSystemInfo 上设置它。也许这会更好地处理 SetCreationTime 的元信息缓存问题。

例如:

static void SetCreationTime(FileSystemInfo fsi, DateTime creationTime)
{
 fsi.CreationTime = creationTime;
}
于 2013-06-15T17:06:08.880 回答
1

再次感谢大家的帮助。我现在一切正常,并且我与所有其他像我一样的初学者分享了所有的工作:

https://github.com/panditarevolution/filestamp

主要代码在 /FileStamp/program.cs

它是一个小型命令行实用程序,允许更改文件的创建日期。我用它作为一个初学者的小项目来教我一些关于 c# 和命令行界面的基础知识。它使用此处提供的有用的 CommandlineParser 库:

http://commandline.codeplex.com/

于 2013-06-18T04:28:27.457 回答
1

在当前 Windows 10 版本的 Visual Studio Community Basic 中,语句

Dim fi As New FileInfo(someFilename)
Dim dtf As Date = CDate(someValidDateString)
fi.CreationTime = dtf
fi.CreationTimeUtc = dtf
fi.LastWriteTime = dtf
fi.LastWriteTimeUtc = dtf
fi.LastAccessTime = dtf
fi.LastAccessTimeUtc = dtf

不适用于文件类型 EML(可能还有其他)。创作作品,其他2部保持不变。我使用此过程每年将我的电子邮件存档在一个文件夹中,并希望能够按名称或修改日期对它们进行排序(因为这些列默认存在于资源管理器中)。在这里我的解决方案是将文件重命名为file+“$”,更改日期,将文件重命名为原始文件。

于 2019-01-01T09:16:51.403 回答