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?
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.
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); } }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With