How to: Copy a Directory to Another Directory in Visual Basic
Use the My.Computer.FileSystem.CopyDirectory Method method to copy a directory to another directory. This method copies the contents of the directory as well as the directory itself. If the target directory does not exist, it will be created. If a directory with the same name exists in the target location and overwrite is set to False, the contents of the two directories will be merged. You can specify a new name for the directory during the operation.
When copying files within a directory, exceptions may be thrown that are caused by specific file, such as a file existing during a merge while overwrite is set to False. When such exceptions are thrown, they are consolidated into a single exception, whose Data property holds entries in which the file or directory path is the key and the specific exception message is contained in the corresponding value.
To copy a directory to another directory
-
Use the CopyDirectory method, specifying source and destination directory names. The following example copies the directory named TestDirectory1 into TestDirectory2, overwriting existing files.
My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system - Processing Drives, Folders, and Files. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
-
The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).
-
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).
-
destinationDirectoryName is Nothing or an empty string (ArgumentNullException)
-
The source directory does not exist (DirectoryNotFoundException).
-
The source directory is a root directory (IOException).
-
The combined path points to an existing file (IOException).
-
The source path and target path are the same (IOException).
-
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be copied (OperationCanceledException).
-
The operation is cyclic (InvalidOperationException).
-
The path contains a colon (:) (NotSupportedException).
-
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 user lacks necessary permissions to view the path (SecurityException).
-
A destination file exists but cannot be accessed (UnauthorizedAccessException).