如何:在 Visual Basic 中将一个目录复制到另一个目录How to: Copy a Directory to Another Directory in Visual Basic

使用 CopyDirectory 方法将一个目录复制到另一个目录。Use the CopyDirectory 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. 如果目标位置中存在具有相同名称的目录,并且 overwrite 设置为 False,则将合并这两个目录的内容。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.

复制目录中的文件时,可能会因特定文件引发异常,例如将 overwrite 设为 False,在合并期间存在的文件。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. 如果引发此类异常,那么这些异常将合并为一个异常,其 Data 属性保存的条目中文件或目录路径为键,特定的异常消息包含在对应的值中。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

  • 使用 CopyDirectory 方法指定源和目标目录名称。Use the CopyDirectory method, specifying source and destination directory names. 下面的示例将名为 TestDirectory1 的目录复制到 TestDirectory2,并覆盖现有文件。The following example copies the directory named TestDirectory1 into TestDirectory2, overwriting existing files.

    My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)
    

    此代码示例也可作为 IntelliSense 代码片段。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 Code Snippets.

可靠编程Robust Programming

以下情况可能会导致异常:The following conditions may cause an exception:

另请参阅See also