jQuery and ASP.NET

August 26, 2009

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.



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

comments

2 Responses to "Using LINQ to Search and Delete Old Files"
  1. Anh Đức said...
    September 16, 2009 1:59 AM

    Thank

  2. Steve said...
    April 9, 2010 7:07 AM

    Thank mate! This works brilliantly.

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions