Delete All Files & Folders from Parent that are older then X Days

 

Simple method here that checks the Creation Time and deletes all files and folders from the parent, recursively that are older then the given number of days.

''' <summary>''' Given the Root Folder, deletes all files and folders older then X days, recursively.''' </summary>''' <param name="RootFolder">DirectoryInfo Object of Root Folder to Delete Files and Subfolders From</param>''' <param name="DeleteOlderThenXDays">Delete files/folders that are older then this many number of days</param>''' <remarks></remarks>Public Sub DeleteAllFilesAndFoldersFromRootFolder(ByVal RootFolder As DirectoryInfo, ByVal DeleteOlderThenXDays As Integer)    Try        DeleteFilesInThisFolder(RootFolder, DeleteOlderThenXDays)        For Each SubFolder As DirectoryInfo In RootFolder.GetDirectories()            DeleteAllFilesAndFoldersFromRootFolder(SubFolder, DeleteOlderThenXDays)            If SubFolder.GetFiles.Count = 0 AndAlso SubFolder.GetDirectories.Count = 0 Then                If SubFolder.CreationTime < (DateAdd(DateInterval.Day, -DeleteOlderThenXDays, Today())) Then SubFolder.Delete()            End If        Next    Catch ex As Exception        Throw ex    End TryEnd Sub

''' <summary>''' Deletes all Files in a Folder''' </summary>''' <param name="Folder">DirectoryInfo Object of Folder to delete files from.</param>''' <param name="DeleteOlderThenXDays">Delete files that are older then this many number of days</param>''' <remarks></remarks>Private Sub DeleteFilesInThisFolder(ByVal Folder As DirectoryInfo, ByVal DeleteOlderThenXDays As Integer)    Try        For Each ExistingFile As FileInfo In Folder.GetFiles()            If ExistingFile.CreationTime < (DateAdd(DateInterval.Day, -DeleteOlderThenXDays, Today())) Then                ExistingFile.Delete()            End If        Next    Catch ex As Exception        Throw ex    End TryEnd Sub

Need the C# Version? Use this.

Response.Redirect Thread Was Being Aborted. Properly Handle this Exception and not with a Try/Catch.

Extending the ASP.NET MVC HtmlHelper in VB.NET Specifically