Results 1 to 3 of 3

Thread: [RESOLVED] How to delete all folders and sub-folders in a path?

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2020
    Posts
    48

    Resolved [RESOLVED] How to delete all folders and sub-folders in a path?

    Hi,
    For learning and testing purpose, I tried to write some codes for deleting all the files and folders in a specific folder in my desktop. I want to develop this code for clearing all files and folders in Temp folder in C:\
    I can delete files but folders can't be deleted and IDE gives "The directory is not Empty"
    Actually, in the folder named "My Files", I have some folders in each other. The code just delete empty folders, not nested folders or folders which contain files.
    How can I revise the code?
    Code:
    Imports System.IO
    Module Module1
        Dim a = My.Computer.FileSystem.SpecialDirectories.Desktop
        Sub Main()
            Console.BackgroundColor = ConsoleColor.Black
            Console.ForegroundColor = ConsoleColor.Yellow
            Console.Clear()
    
            Console.WriteLine("Trying to delete all files and folders...")
            'The following command will keep the console open after its end.
            'Console.ReadLine()
            MsgBox("Your files will be deleted!", MsgBoxStyle.Exclamation, "Message")
    
            Dim path As String = a & "\My Files"
            DeleteDirectory(path)
    
        End Sub
        Private Sub DeleteDirectory(path As String)
    
            If Directory.Exists(path) Then
                'Delete all files from the directory
                For Each filepath As String In Directory.GetFiles(path)
                    IO.File.Delete(filepath)
    
                Next
                'Delete all child directories
                For Each dir As String In Directory.GetDirectories(path)
    
                    IO.Directory.Delete(dir)
                Next
    
            End If
        End Sub
    End Module
    Last edited by fa2020; Aug 3rd, 2020 at 07:59 AM.

  2. #2

    Thread Starter
    Member
    Join Date
    Jun 2020
    Posts
    48

    Re: How to delete all folders and sub-folders in a path?

    Finally, I found my answer.
    I just need to change this line:
    Code:
    IO.Directory.Delete(dir, True)

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: How to delete all folders and sub-folders in a path?

    Please use the Thread Tools menu to mark your thread Resolved if you no longer need assistance.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width