Vivek Chandraprakash
Vivek Chandraprakash

Reputation: 1163

Delete Files that are more than than 10 days old using Linq

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

Answers (2)

Shai Cohen
Shai Cohen

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

Jon Skeet
Jon Skeet

Reputation: 1500595

Well there are two things I'd change:

  • Determine the cut-off DateTime once, rather than re-evaluating DateTime.Now repeatedly
  • I wouldn't use a query expression when you've just got a where 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

Related Questions