Imports System.IO

Namespace PCSolution

    Public Class DirectoryDelete


        Public Sub Delete(sDirectory As String)


            Dim di As New DirectoryInfo(sDirectory)

            Try

                For Each diChild As DirectoryInfo In di.GetDirectories()

                    Try
                        TraverseDirectory(diChild)
                    Catch ex As Exception
                        Exit Sub
                    End Try

                Next

            Catch ex As Exception

            End Try

            CleanAllFilesInDirectory(di)

            Try

                If di.GetFiles().Length = 0 Then

                    di.Delete()

                End If

            Catch ex As Exception

            End Try

        End Sub

        Private Sub TraverseDirectory(ByVal di As DirectoryInfo)

            Try

                For Each diChild As DirectoryInfo In di.GetDirectories()

                    TraverseDirectory(diChild)

                Next

            Catch ex As Exception

            End Try

            CleanAllFilesInDirectory(di)

            If di.GetFiles().Length = 0 Then

                di.Delete()

            End If



        End Sub


        Private Sub CleanAllFilesInDirectory(ByVal DirectoryToClean As DirectoryInfo)

            Try

                For Each fi As IO.FileInfo In DirectoryToClean.GetFiles()

                    If fi.CreationTime < Now.Subtract(New TimeSpan(0, 0, 1)) Then

                        fi.IsReadOnly = False

                        fi.Delete()

                        System.Threading.Thread.Sleep(50)

                    End If

                Next

            Catch ex As Exception

            End Try

        End Sub

    End Class

End Namespace