Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing files that are older than some number of days

Tags:

c#

I guess this is a pretty common requirement in a application that does quite a bit of logging. I am working on a C# Windows application, .NET 3.5.

My app generates tons of log files which has a current date put in the file name like so 20091112. What would be the best strategy to remove files older than say 30 days. One approach I am about to use it, is to loop through the file names, extract the date part, convert into DateTime object and compare with today's date. Is there an elegant Regular Expression solution to this :) ? Or something better?

like image 894
theraneman Avatar asked Nov 12 '09 08:11

theraneman


People also ask

How do I delete 5 days old files in Linux?

The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +5, it will find files older than 5 days. The third argument, -exec, allows you to pass in a command such as rm. The {} \; at the end is required to end the command.


2 Answers

var files = new DirectoryInfo(@"c:\log").GetFiles("*.log"); foreach (var file in files) {     if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(30))     {         File.Delete(file.FullName);     } } 
like image 64
Darin Dimitrov Avatar answered Sep 20 '22 12:09

Darin Dimitrov


update .net 4.0:

var files = new DirectoryInfo(directoryPath).GetFiles("*.log"); foreach (var file in files.Where(file => DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromHours(2))) {      file.Delete(); } 
like image 27
PernerOl Avatar answered Sep 21 '22 12:09

PernerOl