Recursively delete files and directory

  • 13 years ago
    I have been trying to figure out how to delete a directory and all of the subdirectories and files.  Apparently you can't delete a non empty folder.  I have been struggling to get this together...can someone help?

  • 13 years ago

    Try this one:

    Private Sub DeleteAllSubFolders(ByVal StartPath As String)

          Dim myfolder As DirectoryInfo = New DirectoryInfo(StartPath)

          Dim mySubfolders() As DirectoryInfo = myfolder.GetDirectories()

          Dim strFiles() As FileInfo = myfolder.GetFiles()

          'for each folder, do a recursive call to this sub routine

          For Each myItem As DirectoryInfo In mySubfolders

                DeleteAllSubFolders(myItem.FullName)

          Next

          'delete all files in the current folder

          For Each myItem As FileInfo In strFiles

                myItem.Delete()

          Next

    '      delete the starting folder

          myfolder.Delete()

    End Sub

    It's an excellent example of when recursive calls can be used. It's not tested code,and needs to be tested and tweaked for read-only and system files, but the basic design should work.

     

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” - Rick Osborne