Reputation: 1630
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?
Upvotes: 27
Views: 35114
Reputation: 1
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
if (File.GetLastWriteTime(file) < DateTime.Now.AddDays(-5))
{
File.Delete(file);
}
}
Upvotes: 0
Reputation: 417
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();
}
Upvotes: 13
Reputation: 61795
[In PowerShell] you could paste the following into a PS1 file and make it part of an admin script if that suits:-
param($path=$(throw "Need to indicate path"), $daysToRetain=$(throw "Need to indicate how many days to retain"))
dir $path -r | ? { ([datetime]::UtcNow - $_.CreationTimeUtc).TotalDays -gt $daysToRetain } | del
EDIT: And you can use -match
to parse the name if you feel using the file times isnt the right thing to do
Upvotes: 1
Reputation: 4410
As I understand, you want to use file name rather than modification time. Fine.
Then the code is like this:
foreach (string file in Directory.GetFiles(path))
{
string fileNameOnly=Path.GetFileNameWithoutExtension(file);
DateTime fileDate = DateTime.ParseExact(fileNameOnly, "yyyyMMDD", CultureInfo.CurrentCulture);
if (DateTime.Now.Subtract(fileDate).TotalDays > MaxDays)
File.Delete(file);
}
Upvotes: 1
Reputation: 8829
string directoryPath = "/log"; // your log directory path
foreach (string filePath in Directory.GetCreationTime(directoryPath))
{
TimeSpan fileAge = File.GetLastWriteTime(filePath) - DateTime.Now;
if (fileAge.Days > 30)
{
File.Delete(filePath);
}
}
Upvotes: 1
Reputation: 50273
Substracting two DateTime
objects will give you a TimeSpan
object, then you can just check its TotalDays
property. I can't think of anything simpler than this.
Upvotes: 0
Reputation: 1038830
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);
}
}
Upvotes: 37