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 !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s