Using LINQ to Search and Delete Old Files

I was recently asked on the asp.net forum about ways to find old files and delete them. I said use LINQ. It is perfect for this scenario. Here’s the query to do find old files. Add a reference to System.IO

C#

var query = from o in Directory.GetFiles("/YourFolder", "*.*",
SearchOption.AllDirectories)
let x = new FileInfo(o)
where x.CreationTime <= DateTime.Now.AddMonths(-6)
select o;
foreach (var item in query)
{
File.Delete(item);
}

VB.NET

Dim query = _
From o In Directory.GetFiles("/YourFolder", "*.*", _
SearchOption.AllDirectories) _
Let x = New FileInfo(o) _
Where x.CreationTime <= DateTime.Now.AddMonths(-6) _
Select o
For Each item In query
File.Delete(item)
Next item

The query finds all the files, which in this case is all files, where the creation date is six months old. All you need to do to get this working for you is to update the directory to search, and update the search pattern to search for all or only specified files. This functionality can be copied into a console application and run as a scheduled task. Yet another good reason to use LINQ.



Will you give this article a +1 ? Thanks in advance


About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

3 comments:

Anh Đức said...

Thank

Steve said...

Thank mate! This works brilliantly.

Sedat Tiryaki said...

var query = from c in db.haberlerlsts where c.onay == true orderby c.id descending select c;

relationship with the non-scan images in the folder, and delete database