Удалить пустые папки (рекурсия) - PullRequest
0 голосов
/ 27 мая 2020

Почему мой код не работает? Он должен проверить каждую папку на наличие других файлов / директорий, а затем удалить их.

Private Sub DeleteEmptyFolder(ByVal sDirectoryPath As String)
    If Owner.PluginXML.EmptyFolder Then
        Try
            If IO.Directory.Exists(sDirectoryPath) Then
                Dim oDirectory As New IO.DirectoryInfo(sDirectoryPath)
                If oDirectory.GetDirectories.Count = 0 AndAlso oDirectory.GetFiles.Count = 0 Then
                    For Each oDir As IO.DirectoryInfo In oDirectory.GetDirectories
                        Log(oDir.Name)  '''Using Log for testing instead of oDir.Delete(True) 
                    Next
                    For Each folder As IO.DirectoryInfo In oDirectory.GetDirectories()
                        DeleteEmptyFolder(folder.FullName)
                    Next
                End If
            End If
        Catch ex As Exception
            Log("Error DeleteEmptyFolder.", LogLevel.Exception, ex)
        End Try
    End If
End Sub

Ошибок нет, просто не работает / регистрирует пустые папки.

1 Ответ

2 голосов
/ 27 мая 2020

В случае пустого каталога вы никогда не достигнете Delete / Log, потому что он находится внутри перечисления (которое не дает результатов, поскольку GetDirectories ничего не возвращает). Попробуйте вместо этого:

Private Sub DeleteEmptyFolder(ByVal sDirectoryPath As String)
    If Owner.PluginXML.EmptyFolder Then
        Try
            If IO.Directory.Exists(sDirectoryPath) Then
                Dim oDirectory As New IO.DirectoryInfo(sDirectoryPath)
                Dim subDirectories = oDirectory.GetDirectories()
                If subDirectories.Length = 0 AndAlso oDirectory.GetFiles().Length = 0 Then
                    Console.WriteLine("Deleting" + sDirectoryPath)
                    'oDirectory.Delete(True)
                    Return
                End If
                For Each folder As IO.DirectoryInfo In subDirectories
                    DeleteEmptyFolder(folder.FullName)
                Next
            End If


        Catch ex As Exception
            Log("Error DeleteEmptyFolder.", LogLevel.Exception, ex)
        End Try
    End If
End Sub
...