我有一个应用程序,它应该将目录以txtbox1编写的选定文件复制到txtbox2中编写的director文件夹中,如下所示:
代码:
Dim sourcepath As String = TextBox1.Text
Dim DestPath As String = TextBox2.Text
CopyDirectory(sourcepath, DestPath)
叫做子:
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
此代码复制所有文件,而不是仅复制指定的文件。有人可以告诉我如何使这个子副本只选择文件而不是文件夹中的所有文件吗?
答案 0 :(得分:1)
您将整个路径作为参数(类似于:C:/someDirectory/filename.txt)并且不将文件名与该目录中的其他文件名进行比较。
而不是使用:
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
尝试:
Dim sourceFileName = Path.GetFileName(sourcePath)
For Each filePath As String in Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim filename As String = Path.GetFileName(filePath)
If sourceFileName = filename
'Do your copy code here
End If
Next