संपादित करें

इसके माध्यम से साझा किया गया


How to: Move a File in Visual Basic

The My.Computer.FileSystem.MoveFile method can be used to move a file to another folder. If the target structure does not exist, it will be created.

To move a file

  • Use the MoveFile method to move the file, specifying the file name and location for both the source file and the target file. This example moves the file named test.txt from TestDir1 to TestDir2. Note that the target file name is specified even though it is the same as the source file name.

    My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
        "C:\TestDir2\test.txt")
    

To move a file and rename it

  • Use the MoveFile method to move the file, specifying the source file name and location, the target location, and the new name at the target location. This example moves the file named test.txt from TestDir1 to TestDir2 and renames it nexttest.txt.

    My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
        "C:\TestDir2\nexttest.txt",
        FileIO.UIOption.AllDialogs,
        FileIO.UICancelOption.ThrowException)
    

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).

  • destinationFileName is Nothing or an empty string (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, onUserCancel 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).

See also