I commonly write applications that will write a new log file every day, and as you can imagine, over time this be be quite a task to keep things clean and tidy. I recently found that LINQ is perfect for this scenario.
Just be sure to have a reference to System.IO and then here is the code you need:
C#
1 2 3 4 5 6 7 8 | 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
1 2 3 4 5 6 7 8 9 10 | 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 |
Summary
The code above will find all files older than 6 months, and delete them. Be sure if you use this code to update the search directory, and to change the search pattern (“*.*”) to only delete the files you intend to delete.
Popularity: 100%



Hey this is great. I needed just this functionality for a school project.