Question

The below Sub searches through some folders and deletes any empty ones (Unless the folder is called Bars or Backup)

sPath is set to c:\temp\working\ and the folders that should be scanned and deleted if empty are sub-directories of Working

The sub does the job however if it gets to the point where all the sub-directories are empty and have been removed then the folder Working is then deleted which is not what I need to happen.

Any suggestions on how to stop this, or do i need to recreate the directory if it gets to that stage (not ideal)

  Public Sub DeleteEmptyFolders(ByVal sPath As String)

    Dim SubDirectories() As String = Directory.GetDirectories(sPath)
    For Each strDirectory As String In SubDirectories
        DeleteEmptyFolders(strDirectory)
    Next
    If Not (UCase(Path.GetDirectoryName(sPath)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(sPath)).Contains("BARS")) Then
        If Directory.GetFiles(sPath).Length + Directory.GetDirectories(sPath).Length = 0 Then
            Directory.Delete(sPath)
            MsgBox("Deleting empty folder: " & sPath)
        End If
    End If
End Sub

Thanks

Was it helpful?

Solution

A first approach to solve the problem could be to pass the starting root and do not delete the directory if it is the starting root

Public Sub DeleteEmptyFolders(ByVal sPath As String, ByVal sRoot As String)

    Dim SubDirectories() As String = Directory.GetDirectories(sPath )
    For Each strDirectory As String In SubDirectories
        DeleteEmptyFolders(strDirectory, sRoot)
    Next
    If Not (UCase(Path.GetDirectoryName(sPath)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(sPath)).Contains("BARS")) Then
        If Directory.GetFiles(sPath).Length + Directory.GetDirectories(sPath).Length = 0 Then
            if sPath <> sRoot Then
                Directory.Delete(sPath)
                Console.WriteLine("Deleting empty folder: " & sPath)
            End If
        End If
    End If
End Sub

Call with

DeleteEmptyFolders("D:\temp", "D:\temp")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top