Export (0) Print
Expand All

How to: Delete a Directory in Visual Basic 

Use the DeleteDirectory method of the My.Computer.FileSystem object to delete a directory. Among the options are: whether or not to delete the directory's contents, whether or not to send the deleted directory to the Recycle Bin, and whether or not to show the progress of the deletion.

To delete a directory only if it is empty

  • Use the DeleteDirectory method to delete the directory, specifying False for onDirectoryNotEmpty. This example deletes the directory named OldDirectory only if it is empty.

    My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", _
    FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
    
    

To delete a directory and send it to the Recycle Bin

  • Use the DeleteDirectory method to delete the directory, specifying RecycleOption.SendToRecycleBin for recycle. This example deletes the directory named OldDirectory and all of its contents, sending them to the Recycle Bin and showing the operation progress.

    My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin)
    
    

Robust Programming

The following conditions may cause an exception:

  • The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including wildcard characters) (ArgumentException).

  • The path is a device path (starts with \\.\) (ArgumentException).

  • The path is Nothing (ArgumentNullException).

  • The directory does not exist or is a file (DirectoryNotFoundException).

  • The user does not have permission to delete the directory or subdirectory (IOException).

  • A file in the directory or subdirectory is in use (IOException).

  • A file or directory name contains a colon (:) (NotSupportedException).

  • OnUserCancel is set to ThrowException and the user cancels the operation (OperationCanceledException).

  • OnUserCancel is set to ThrowException and the directory cannot be deleted (OperationCanceledException).

  • The path exceeds the system-defined maximum length (PathTooLongException).

  • showUI is set to AllDialogs and the user does not have required permissions (UnauthorizedAccessException).

See Also

Community Additions

ADD
Show:
© 2014 Microsoft