Export (0) Print
Expand All

How to: Create a Copy of a File in the Same Directory in Visual Basic

Use the My.Computer.FileSystem.CopyFile method to copy files. The parameters allow you to overwrite existing files, rename the file, show the progress of the operation, and allow the user to cancel the operation.

To create a copy of a file in the same folder

  • Use the CopyFile method, supplying the target file and the location. The following example creates a copy of test.txt called test2.txt.

    My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
    "C:\TestFolder\test2.txt", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
    

To create a copy of a file in the same folder, overwriting existing files

  • Use the CopyFile method, supplying the target file and location, and setting overwrite to True. The following example creates a copy of test.txt called test2.txt and overwrites any existing files by that name.

    My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
    "C:\TestFolder\test2.txt", True)
    

The following conditions may cause an exception to be thrown:

  • 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 system could not retrieve the absolute path (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 (IOException).

  • The destination file exists and overwrite is set to False (IOException).

  • The user does not have sufficient permissions to access the file (IOException).

  • A file in the target folder with the same name is in use (IOException).

  • A file or folder 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 the user has cancelled the operation (OperationCanceledException).

  • ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs (OperationCanceledException).

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

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

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

Show:
© 2014 Microsoft