Delete files older than 3 months old in a directory using .NET
Solution 1
Something like this outta do it.
using System.IO;
string[] files = Directory.GetFiles(dirName);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
fi.Delete();
}
Solution 2
Here's a 1-liner lambda:
Directory.GetFiles(dirName)
.Select(f => new FileInfo(f))
.Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
.ToList()
.ForEach(f => f.Delete());
Solution 3
For those that like to over-use LINQ.
(from f in new DirectoryInfo("C:/Temp").GetFiles()
where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
select f
).ToList()
.ForEach(f => f.Delete());
Solution 4
Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):
DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);
// Get info of each file into the directory
foreach (FileInfo fi in source.GetFiles())
{
var creationTime = fi.CreationTime;
if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
{
fi.Delete();
}
}
Solution 5
The most canonical approach when wanting to delete files over a certain duration is by using the file's LastWriteTime (Last time the file was modified):
Directory.GetFiles(dirName)
.Select(f => new FileInfo(f))
.Where(f => f.LastWriteTime < DateTime.Now.AddMonths(-3))
.ToList()
.ForEach(f => f.Delete());
(The above based on Uri's answer but with LastWriteTime
.)
Whenever you hear people talking about deleting files older than a certain time frame (which is a pretty common activity), doing it based on the file's LastModifiedTime is almost always what they are looking for.
Alternatively, for very unusual circumstances you could use the below, but use these with caution as they come with caveats.
CreationTime
.Where(f => f.CreationTime < DateTime.Now.AddMonths(-3))
The time the file was created in the current location. However, be careful if the file was copied, it will be the time it was copied and CreationTime
will be newer than the file's LastWriteTime
.
LastAccessTime
.Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
If you want to delete the files based on the last time they were read you could use this but, there is no guarantee it will be updated as it can be disabled in NTFS. Check fsutil behavior query DisableLastAccess
to see if it is on. Also under NTFS it may take up to an hour for the file's LastAccessTime to update after it was accessed.
Comments
-
JL. over 2 years
I would like to know (using C#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible.
Just to be clear: I am looking for files that are older than 90 days, in other words files created less than 90 days ago should be kept, all others deleted.
-
JL. over 14 yearsThanks, I noticed you're using lastAccessTime, is this the creation time?
-
Admin over 14 yearsno, as propertyNames says:
LastAccessTime
- you should go for propertyCreationTime
if you'd like to! -
Steve Danner over 14 yearsYeah, which property you use is entirely up to you. You could also use LastWriteTime if you wanted.
-
JL. over 14 yearsSorry to ask, but are you 100% sure about the comparison operator being less than? does this mean that the first date should be less than the 2nd date?
-
Steve Danner over 14 yearsNo need to apologize, that is how you learn! Yes, I'm positive. It means the last access time on the file is less than the date 3 months ago from this moment.
-
JL. over 14 yearsOk thanks Steve, you got here first with a great answer, thanks again!
-
Ta01 over 14 yearsvar filesToDelete = new DirectoryInfo(@"C:\Temp").GetFiles().Where(x=>x.LastAccessTime < DateTime.Now.AddMonths(-3)); //variation
-
Filip Ekberg over 14 yearsWoho! Someone else than me thinks over-using LINQ is awesome! ;)
-
Joel Mueller over 14 yearsWhat does the
.ToList()
call add other than a second loop through the matched files? -
JamesUsedHarden over 14 years@Joel Mueller.
List<T>
defines aForEach
method which can be used to apply anAction<T>
to all elements. Unfortunately there is no such extension method forIEnumerable<T>
. -
Joel Mueller over 14 yearsGood point. I wrote my own
ForEach
extension method forIEnumerable<T>
so long ago, I sometimes forget it isn't built in. -
Dynami Le Savard over 14 yearsNo need for
ToList()
,DirectoryInfo.GetFiles()
returns aFileInfo[]
. -
Mario The Spoon about 13 years+1 for helping me out. Instead of creating a new FileInfo instance you could use File.GetCreationTime or File.GetLastAccessTime. Should be a minor performance improvement.
-
abrkn over 11 yearsFor those with no shame:
new DirectoryInfo(@"C:\Temp").GetFiles("*.log").AsParallel().Where(f => f.LastWriteTime < DateTime.Now - TimeSpan.FromDays(90)).ForAll(f => f.Delete());
-
JamesUsedHarden over 11 yearsSince the tasks are all reading/writing from the same disk I'm not sure
AsParallel
is really appropriate here. It'd be good to test to be sure. -
Andrew Hagner almost 11 yearsI guess GetFiles and Delete never fail in your environment? Just pointing that out since this seems to be a highly referenced answer.
-
Andrew Hagner almost 11 yearsHow would you handle a failed call to Delete via this Linq version?
-
JamesUsedHarden over 10 years@AndrewHagner, I would add a new utility method like
DeleteSafe()
and include error handling in that to never throw an error even if delete fails. -
Daniel over 7 years90 days <> 3 months
-
James Love over 7 years@VladL I get a "IEnumerable<FileInfo> does not contain ForEach" if I drop the ToList(). I just kept it in.
-
Chad about 7 yearsYou should declare a new variable outside the
foreach()
loop to hold the value of(DateTime.Now- new TimeSpan(90, 0, 0, 0))
. There is no reason to calculate that repeatedly in the loop. -
H20rider about 7 yearsI like this. But I would wrap the delete in a try/catch
-
Allan F about 5 yearsLastWriteTime is the datetime visible in standard file explorer .. I'm going with a test against this attribute. Yep - I would put in a try catch ..
-
Vojtěch Dohnal almost 5 years
new DirectoryInfo(dir).GetFiles()
is faster thannew FileInfo(f)
for every single file. -
Armando Contestabile about 2 yearsWhy do evaluate each loop DateTime.Now.AddMonths(-3) ?