VB.NET to Delete files older than 30 days from folder

So, I wrote a comparison logic that would check the individual file to 30 days old with DateTime.Compare and wanted to share it in case it helps someone.
I display the deleted file, the date it was created as well as the files which aren’t deleted with their creation date in two lists in the ASPCA page. Btw this is in VB.NET

For Each aFile In Files
Try
Dim beforeThisDate As Date = DateAndTime.Today.AddDays(-30)
Dim thisFileModifiedDate As Date = System.IO.File.GetLastWriteTime(strFilePath & aFile.ToString())
Dim htmlNewLine As String = “

Dim result As Integer = DateTime.Compare(thisFileModifiedDate, beforeThisDate)
If result < 0 Then
'MsgBox(thisFileModifiedDate + " Is earlier than " + beforeThisDate)
lblDeletedFiles.Text += aFile.ToString + " Date created:" + thisFileModifiedDate + htmlNewLine
deleteCount = deleteCount + 1
System.IO.File.Delete(Folder + aFile.ToString())
ElseIf result = 0 Then
'MsgBox(thisFileModifiedDate + " Is the same as " + beforeThisDate)
lblNotDeletedFiles.Text += aFile.ToString + " Date created:" + thisFileModifiedDate + htmlNewLine
notDeletedCount = notDeletedCount + 1
Else
'MsgBox(thisFileModifiedDate + " Is later than " + beforeThisDate)
lblNotDeletedFiles.Text += aFile.ToString + " Date created:" + thisFileModifiedDate + htmlNewLine
notDeletedCount = notDeletedCount + 1
End If
Catch ex As Exception
LcpsUtilities.RecordError(ex.Message, "RecycleIcsEvents.delete file section")
End Try
lblDeletedCount.Text = deleteCount.ToString
lblNotDeletedCount.Text = notDeletedCount.ToString
Next

The files on the folder that are older than 30 days are now deleted.
Good luck !


Discover more from QubitSage Chronicles

Subscribe to get the latest posts sent to your email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.