Question Delete folder content

ElectricalStorm

New member
Joined
Oct 14, 2009
Messages
2
Programming Experience
3-5
Hi all,

How can I clear an existing folder with vb.net? I already searched the internet, but the code I found only deleted the files and left the subfolders in place. Of course I could delete the folder and immediately recreate it, but in a next stage I want to delete specific files (for instance: .lng files) and leave the other files alone.

Perhaps those will be two totally different functions… I recently stopped good old vb6 and the above actions could be done with two look alike functions.

Thanks in advance,
Chris
 
So then you would want to do a series of File.Delete() and Directory.Delete() in a loop given a path. Here's a start for ya:
VB.NET:
Imports System.IO

Private Sub ClearFolder(ByVal Folder As String)
  For Each item As String In Directory.GetFileSystemEntries(Folder)
    If Directory.Exists(item) Then
      'Is a folder
    Else
      'Is a file
    End If
  Next item
End Sub
 
The easiest would be to deleted the whole folder with content with one call and create a new folder with same name with a second call.
VB.NET:
IO.Directory.Delete(path, True)
IO.Directory.CreateDirectory(path)
 
Thanks but I don’t want to delete a specific file or folder, I want to delete the content of a specific folder.
And what do you think the subfolders of that specific folder are? They are specific folders. You call Directory.GetFiles to get all the files and then call File.Delete to delete each one. You call Directory.GetDirectories to get all the subfolders and then call Directory.Delete to delete each one.
 
The easiest would be to deleted the whole folder with content with one call and create a new folder with same name with a second call.
VB.NET:
IO.Directory.Delete(path, True)
IO.Directory.CreateDirectory(path)
That makes 5 now...

The only reason why you wouldn't want to do it this way is if a subfolder (or file) is one you don't have permission to delete, in which the thing crashes on that and doesn't continue to delete the rest of what it can. If you put error handling in the middle of the sub I started, you can have it skip the one's that wont delete. It's a matter of requirements and preferences though.
 
Back
Top