How to: Move a Collection of Files in Visual Basic

The My.Computer.FileSystem.MoveFile method allows you to move files between directories.

If the target structure does not exist, it will be created.

To move a collection of files from one directory to another

  • Define the collection of files and call the MoveFile method. This example moves all files in the directory MyDocuments to the folder StorageDir.

    For Each foundFile As String In My.Computer.FileSystem.GetFiles(
        Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.*")
        Dim foundFileInfo As New System.IO.FileInfo(foundFile)
        My.Computer.FileSystem.MoveFile(foundFile, "C:\StorageDir\" & foundFileInfo.Name)

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 source file is not valid or does not exist (FileNotFoundException).

  • The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the target directory with the same name is in use, or the user does not have sufficient permissions to access the file (IOException).

  • A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

  • showUI is set to True, onUserCancelOption is set to ThrowException, and either the user has cancelled the operation or an unspecified I/O error occurs (OperationCanceledException).

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

  • The user lacks necessary permissions to view the path (SecurityException).

  • The user does not have required permission (UnauthorizedAccessException).

Community Additions