删除不是日期的旧文件 [英] Delete files older than a date

查看:133
本文介绍了删除不是日期的旧文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个C#程序,我检查文件的创建时间和删除,如果该文件是超过2天以上。我有下面的代码片段应实现这一目标。

I am currently working on a c# program where I check the creation time of a file and delete it if the file is older than 2 days. I have the following code snippet that should be achieving this.

DateTime creationTime = file.CreationTime.Date;
if (creationTime < DateTime.Now.AddDays(-logAge) && file.Name != currentLog)
{
    File.Delete(string.Format("{0}/{1}", directory, file));
}



虽然我的程序正在运行,是不断创造新的文件和一个单独的线程检查超过例如2天的文件也不老。如果我有我的电脑的日期设置为4月24日的文件被创建并保持如预期,如果我再更改电脑的日期为4月25日我希望这些文件仍然因为他们年龄不超过2天,但是,这是不是因为他们被删除的情况。

While my program is running it is constantly creating new files and a separate thread checks that the files are no older than say 2 days. If I have my PC's date set to the 24th April the files are created and kept as expected, if I then change the PC's date to the 25th April I would expect the files to remain as they are not older than 2 days, however, this is not the case as they are being deleted.

日志期限设置为,所以我也没有想到要删除的文件,直到后,我改变了日期为在4月26日。

Log age is set to so I wouldn't have expected files to be deleted until after I had changed the date to be the 26th April.

我在做什么错了,我已经看了很多例子,包括#2的使用删除目录超过3个月的旧文件,.NET 但它没有这样做我会指望它。

What am I doing wrong, I've looked at many examples including another question on Stackoverflow Delete files older than 3 months old in a directory using .NET but its not doing what I would expect it to.

推荐答案

file.Delete确实更有意义比File.Delete(路径)和Path.Combine()使得很多更有意义比使用的String.format。

file.Delete does make more sense than File.Delete(path) and Path.Combine() makes a lot more sense than using string.Format.

我碰到这个答案迷迷糊糊的,不知道为什么,我没有对谷歌花费年龄后的前手找到它,但是这似乎已经解决了这一问题。 DateTime.Compare如何检查日期不到30天?。另一个问题是,我用的是文件的创建时间但我的情况做了它对使用lastWriteTime.date更有意义。

I've stumbled across this answer, don't know why I didn't find it before hand after spending ages on google, but this appears to have fixed the problem. DateTime.Compare how to check if a date is less than 30 days old?. The other problem was that I was using the file creation time but for my scenario it made more sense to use lastWriteTime.date.

这篇关于删除不是日期的旧文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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