Delete old backup files using Script Task and VB.Net

  • Hi,

    I'm trying to use the SSIS Script Task and VB.Net to delete backup files n days old.  I also want to be able to traverse any subdirectories and delete those files. 

    I'm able to get my code to delete files from the root directory, but not sure how to get it to traverse the subdirectories and delete those files.

    Can someone please help me with my problem or know of another method to achieve the same results?  Existing code is below:

    Public Sub Main()

     Dim BackupDirectory As String

     Dim DaysOld As Integer

     Dim FileExtension As String

     BackupDirectory = CType(Dts.Variables("Backup_Path").Value, String)

     DaysOld = CType(Dts.Variables("Days_Old").Value, Integer)

     DeleteFilesNDaysOld(BackupDirectory, DaysOld)          

    End Sub

    Public Sub DeleteFilesNDaysOld(ByVal BackupDirectory As String, ByVal DaysOld As Integer)

       ' Delete files in a particular directory that are n days old

       '   BackupDirectory - directory to look in (does not recursively handle sub-dirs)

       '   DaysOld - number of days old (if 3, then only today, yesterday, and day-before are not deleted)

       '   FileExtension - file extension of files to delete (use "*" for all files)

       Dim DirectoryToDeleteFiles As System.IO.Directory

       Dim FileArray() As String = DirectoryToDeleteFiles.GetFiles(BackupDirectory, "*.bak")

       Dim i As Integer

       For i = 0 To FileArray.GetUpperBound(0)

       Dim TmpFileInfo As System.IO.FileInfo = New System.IO.FileInfo(FileArray(i).ToString)

       Dim DateLastWritten As Date = TmpFileInfo.LastWriteTime

       Dim DateToKill As Date = TmpFileInfo.LastWriteTime.AddDays(DaysOld)

       If DateToKill < Now Then

            System.IO.File.Delete(FileArray(i))

            Dts.TaskResult = Dts.Results.Success

       End If

       Next

     End Sub

    Thanks for your help.

    Tim

  • I've created a very basic example for you below of how you can do it.

    Regards

    Daniel

    '=======================================

    Module Module1

    Const FOLDER = "C:\Windows"

    Sub Main()

    GetSubFolders(FOLDER)

    End Sub

    Sub GetSubFolders(ByVal sSearchPath As String)

    Dim sFolder As String

    For Each sFolder In System.IO.Directory.GetDirectories(sSearchPath)

    'Do something

    Console.WriteLine(sFolder)

    'Call me again

    GetSubFolders(sFolder)

    Next

    End Sub

    End Module

  • Got it to work.  Thanks for your help.

    Tim

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply