Reputation: 1163
i'm using the code below to delete the files that are more than 10 days old. Is there a simpler/smarter way of doing this?
string source_path = ConfigurationManager.AppSettings["source_path"];
string filename= ConfigurationManager.AppSettings["filename"];
var fileQuery= from file in Directory.GetFiles(source_path,filename,SearchOption.TopDirectoryOnly)
where File.GetCreationTime(file)<System.DateTime.Now.AddDays(-10)
select file;
foreach(var f in fileQuery)
{
File.Delete(f);
}
Upvotes: 1
Views: 2204
Reputation: 6249
It is possible to do a LINQ "one-liner" to perform this process:
Directory.GetFiles(source_path,filename,SearchOption.TopDirectoryOnly)
.Where(f => File.GetCreationTime(file) < System.DateTime.Now.AddDays(-10))
.All(f => {File.Delete(f); return true;);
Don't forget to wrap the code in a try catch.
Upvotes: -1
Reputation: 1500595
Well there are two things I'd change:
DateTime
once, rather than re-evaluating DateTime.Now
repeatedlywhere
clause:So I'd rewrite the query part as:
var cutoff = DateTime.Now.AddDays(-10);
var query = Directory.GetFiles(sourcePath, filename, SearchOption.TopDirectoryOnly)
.Where(f => File.GetCreationTime(f) < cutoff);
Another alternative would be to use DirectoryInfo
and FileInfo
:
var cutoff = DateTime.Now.AddDays(-10);
var path = new DirectoryInfo(sourcePath);
var query = path.GetFiles(filename, SearchOption.TopDirectoryOnly)
.Where(fi => fi.CreationTime < cutoff);
(In .NET 4 you might also want to use EnumerateFiles
instead.)
Upvotes: 6