Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

Delete files older than dayofyear

In my code below I am getting the newest file in a folder
Then setting day of year variable(dtYear) from that files last write time

What I would like to do is delete all files in that folder OLDER that dtYear - 2
So that I always have three days of files in the folder.

Private Sub getFiles()
        Try
            Dim appPath As String = Application.StartupPath
            Dim strPath As String
            strPath = File.ReadAllLines(Path.GetFullPath("directorypath.txt")).First() '"C:\Program FIles\"
            Dim di As New System.IO.DirectoryInfo(strPath)
            Dim files As New List(Of System.IO.FileInfo)
            files.AddRange(di.GetFiles())
            files.Sort(AddressOf SortFilesDescendingByLastWriteTime)
            Dim newestFile As System.IO.FileInfo = files(0)
            Dim dtYear = newestFile.LastWriteTime.DayOfYear
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Function SortFilesDescendingByLastWriteTime(ByVal fiA As System.IO.FileInfo, ByVal fiB As System.IO.FileInfo) As Integer
        Return fiB.LastWriteTime.CompareTo(fiA.LastWriteTime)
    End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kimputer
Kimputer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Larry Brister

ASKER

Perfect... thanks.

Watch for follow-up