Create Code that will delete a file based on age.

supersasizza

Member
Joined
Sep 9, 2005
Messages
6
Programming Experience
1-3
Hi all,

I want to create some code that will remove any files in a folder if they are more than 2 months old.

Can anyone help me with this?

I'm a novice in programming and I just wanted to know if anyone would be nice enought to help me.

Thank you,

Antonio
 
This code will do that, the objects and function used to accomplish the task is DirectoryInfo and FileInfo classes from the System.IO namespace. The first got a method to return all the files as FileInfo objects. The FileInfo got properties for creation date and last write date etc. Date type with property Now and method Subtract are bits of the puzzle that will return a TimeSpan structure with lots of useful properties. Longest timespan is TotalDays, so 60 is an approximation to 2 months. Finally the FileInfo allow for Delete method.
VB.NET:
Sub twomonths()
  Dim dir As New IO.DirectoryInfo("c:\temp")
  Dim files() As IO.FileInfo = dir.GetFiles
  Dim datenow As Date = Date.Now
  Dim ts As TimeSpan
  For Each fil As IO.FileInfo In files
    ts = datenow.Subtract(fil.LastWriteTime)
    If ts.TotalDays > 60 Then fil.Delete()
  Next
End Sub
 
Back
Top