此方法 My.Computer.FileSystem.CopyFile
允许复制文件。 其参数提供覆盖现有文件、重命名文件、显示操作进度,并允许用户取消操作的功能。
将文本文件复制到另一个文件夹
CopyFile
使用该方法复制文件,并指定源文件和目标目录。 通过overwrite
参数,可以指定是否覆盖现有文件。 以下代码示例演示如何使用CopyFile
。' Copy the file to a new location without overwriting existing file. My.Computer.FileSystem.CopyFile( "C:\UserFiles\TestFiles\testFile.txt", "C:\UserFiles\TestFiles2\testFile.txt") ' Copy the file to a new folder, overwriting existing file. My.Computer.FileSystem.CopyFile( "C:\UserFiles\TestFiles\testFile.txt", "C:\UserFiles\TestFiles2\testFile.txt", Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing) ' Copy the file to a new folder and rename it. My.Computer.FileSystem.CopyFile( "C:\UserFiles\TestFiles\testFile.txt", "C:\UserFiles\TestFiles2\NewFile.txt", Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
可靠的编程
以下情况可能会导致异常:
路径对于以下原因之一无效:它是一个长度为零的字符串,它只包含空格,它包含无效字符,或者它是设备路径(以 \\.\) 开头(ArgumentException)。
系统无法检索绝对路径(ArgumentException)。
路径无效,因为它是
Nothing
(ArgumentNullException)。源文件无效或不存在(FileNotFoundException)。
组合路径指向现有目录(IOException)。
目标文件存在并
overwrite
设置为False
(IOException)。用户没有足够的权限来访问文件(IOException)。
目标文件夹中具有相同名称的文件正在使用 (IOException)。
路径中的文件或文件夹名称包含冒号(:)或格式无效(NotSupportedException)。
ShowUI
设置为True
,onUserCancel
设置为ThrowException
,并且用户已取消操作(OperationCanceledException)。ShowUI
设置为True
,onUserCancel
设置为ThrowException
,并且发生未指定的 I/O 错误(OperationCanceledException)。路径超过系统定义的最大长度(PathTooLongException)。
用户没有所需的权限(UnauthorizedAccessException)。
用户缺少查看路径所需的权限(SecurityException)。