Link to home
Start Free TrialLog in
Avatar of XK8ER
XK8ERFlag for United States of America

asked on

vb.net - remove empty directories

hello there,
I have a path lets say "c:\names" that contains about 300 different directories..
I would like to create a button that will look through all of the sub-directories and remove the empty ones..
how can I do that?
Avatar of PagodNaUtak
PagodNaUtak
Flag of Philippines image

Try this link

https://www.experts-exchange.com/questions/22839113/Check-for-and-delete-empty-folders.html?sfQueryTermInfo=1+10+30+empti+folder+remov

Below is the accepted answer from TheLearnedOne:

Imports System.IO

Public Class DirectoryCleaner

    ''' <summary>
    ''' Search through sub-directories, and remove any empty ones.
    ''' </summary>
    ''' <param name="path">The folder path to the directory</param>
    Public Shared Sub RemoveEmptyFolders(ByVal path As String)
        Dim directory As New DirectoryInfo(path)
        For Each subDirectory As DirectoryInfo In directory.GetDirectories()
            If subDirectory.GetFiles().Length = 0 Then
                subDirectory.Delete()
            End If
        Next subDirectory
    End Sub

End Class

Example:
    DirectoryCleaner.RemoveEmptyFolders("c:\temp")

Open in new window

Avatar of XK8ER

ASKER

this is what im getting..


The directory is not empty.
>>subDirectory.Delete()
Try the below code instead

'Here's the code:
    Public Sub CheckFolder(ByVal sourceFolderPath As String)
        Dim di As New IO.DirectoryInfo(sourceFolderPath)
        For Each directory As IO.DirectoryInfo In di.GetDirectories
            If directory.GetFiles().Length = 0 AndAlso directory.GetDirectories.Length = 0 Then
                directory.Delete()
            End If
        Next
    End Sub

Open in new window

Avatar of XK8ER

ASKER

the new code its not removing any directories..
ASKER CERTIFIED SOLUTION
Avatar of PagodNaUtak
PagodNaUtak
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of XK8ER

ASKER

thanks a lot.. it works so good..