更改文件创建日期不起作用

时间:2013-06-15 15:51:37

标签: c# datetime

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

using System.IO;

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

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

我在Dropbox文件夹中以及随机文件夹中尝试了此操作

DateTime newCreate对象似乎是正确的。

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

6 个答案:

答案 0 :(得分:23)

实际上,每个文件三次

  1. 创作时间
  2. 上次访问时间
  3. 上次写入时间(在资源管理器和其他文件管理器中显示为“文件日期”)
  4. 要修改这些时间,您可以使用

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

答案 1 :(得分: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 方法并缓存有关文件的信息。在随后的通话中,您 必须致电刷新以获取最新信息。

嗯...显然不尽然。它似乎会自动刷新。

答案 2 :(得分:1)

您可以使用此代码示例

string fileName = @"C:\MyPath\MyFile.txt"; 
if (File.Exists(fileName)) 
{       
    DateTime fileTime = DateTime.Now; 
    File.SetCreationTime(fileName, fileTime);         
}

答案 3 :(得分:1)

再次感谢大家的帮助。我现在一切都工作了,我和其他像我这样的初学者分享了所有的工作:

https://github.com/panditarevolution/filestamp

主要代码位于/FileStamp/program.cs

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

http://commandline.codeplex.com/

答案 4 :(得分: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 +“ $”,更改日期,将文件重命名为原始文件。

答案 5 :(得分:0)

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

例如:

static void SetCreationTime(FileSystemInfo fsi, DateTime creationTime)
{
 fsi.CreationTime = creationTime;
}
相关问题