Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
}
Posted

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.

wrote:
intDays


Just to add - Hungarian notation went out of fashion as soon as the Hungarian stopped working for Microsoft.
 
Share this answer
 
v2
I'd probably do it like this:
C#
DateTime firstValidDate = DateTime.Now.AddDays(-days);
DateTime fileModDate = File.GetLastWriteTime(f);
if (fileModDate < firstValidDate) File.Delete(f);

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).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900