Delete the contents of a directory

This snippet explains how you can delete the contents of a directory with deleting the contents itself, as the folder could have sharing information etc. It also explains how to do it, the .NET way.

''' <summary>
''' Deletes the contents of a directory.
''' </summary>
''' <param name="dir">Directory to delete the contents of.</param>

Public Sub DeleteDirContents(ByVal dir As IO.DirectoryInfo)
    Dim fa() As IO.FileInfo
    Dim f As IO.FileInfo

    fa = dir.GetFiles

    For Each f In fa
        f.Delete()
    Next

    Dim da() As IO.DirectoryInfo
    Dim d1 As IO.DirectoryInfo

    da = dir.GetDirectories
    For Each d1 In da
        DeleteDirContents(d1)
    Next
End Sub

' To use the subroutine, use this code inside a subroutine.
' "c:\lol" being the path you would like to use.
DeleteDirContents(New IO.DirectoryInfo("c:\lol"))

See Also

Dream In Code Submission - http://www.dreamincode.net/code/snippet1426.htm

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License