How to: Delete All Files in a Directory in Visual Basic
The DeleteFile method of the My.Computer.FileSystem object allows you to delete a file. Among the options it offers are: whether to send the deleted file to the Recycle Bin, whether to ask the user to confirm that the file should be deleted, and what to do when the user cancels the operation.
To delete all of the files in a folder
Use the My.Computer.FileSystem.GetFiles method to return the collection of strings representing the files in the directory.
Use a For…Each loop with the DeleteFile method to delete each file in turn.
The following example deletes all files in the My Documents folder.
For Each foundFile As String In My.Computer.FileSystem.GetFiles( My.Computer.FileSystem.SpecialDirectories.MyDocuments, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.*") My.Computer.FileSystem.DeleteFile(foundFile, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently) Next
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to ThrowException (OperationCanceledException).
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
How to: Rename a File in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic