比较“最后修改日期".到今天为止 [英] Comparing the "last modified date" to todays date
问题描述
问候,
我正在编写一个小型实用程序,用于比较文件夹中所有文件的上次修改时间"属性,如果它们的使用天数是X天,则将其删除.
有人能给我比我想出的更优雅的方法吗?
Greetings,
I am writing a small utility that compares the ''Last modified'' attribute on all files in a folder, and if they are X amount of days old, deletes them.
Can someone give me a more elegant way to do this than what I have come up with?
DateTime fileModDate = File.GetLastWriteTime(f);
int result = DateTime.Compare(fileModDate.AddDays(intDays), today);
if (result < 0)
{
File.Delete(f);
}
推荐答案
不,我认为没有任何更简单的方法可以编写此代码.我将File.Delete放入try/catch并考虑检查文件是否为只读,但这会添加代码,但不会将其减去.
No, I don''t think there''s any simpler way of writing this code. I''d put the File.Delete in a try/catch and consider checking if files are read only, but that adds code, it does not subtract it.
intDays
只是要补充-匈牙利语表示法在匈牙利语停止为Microsoft工作后就过时了.
Just to add - Hungarian notation went out of fashion as soon as the Hungarian stopped working for Microsoft.
我可能会这样:
I''d probably do it like this:
DateTime firstValidDate = DateTime.Now.AddDays(-days);
DateTime fileModDate = File.GetLastWriteTime(f);
if (fileModDate < firstValidDate) File.Delete(f);
您可以预先计算 firstValidDate
,然后在循环(例如,对文件夹中每个文件的循环)中使用它,而无需重新进行计算.请注意,也无需使用Compare方法(您可以只使用比较运算符).
You can calculate firstValidDate
in advance then use it in a loop (such as a loop over each file in a folder) without recalculating again. Note that there is also no need to use the Compare method (you can just use comparison operators).
这篇关于比较“最后修改日期".到今天为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!