【问题标题】:Copying a file from a directory to another one将文件从目录复制到另一个目录
【发布时间】:2017-11-18 08:19:45
【问题描述】:

我有一个应用程序,它应该将其目录写入 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

此代码复制所有文件,而不是仅复制指定的文件。有人能告诉我如何让这个子副本只复制选定的文件而不是文件夹中的所有文件吗?

【问题讨论】:

  • 没有什么可以选择的。 Selected *how - 用户应该选择它们吗?请澄清并阅读How to Ask 并采取tour
  • 选择的文件是什么?没有任何类型的数组,比如说,选定的文件
  • 感谢您的评论我已经更新了我的问题,希望它现在提供足够的信息。
  • @ahmedseif 您的问题仍然没有真正表明用户如何选择他们想要复制的文件。你有存储要复制的文件名的变量吗?
  • 文件的目录在 txtbox1 中,文件夹的目录(文件将被复制到)在 textbox2 中,第一个文本框从打开的文件对话框中获取它的值,第二个文本框从一个文件夹浏览器对话框。我认为只要知道这两个目录都存储在 txtbox1 和 txtbox2 值就可以了,我并不在意用户将如何选择文件。

标签: vb.net file-copying


【解决方案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

【讨论】:

  • 最好使用Path.GetFileName 方法从路径中提取文件名,而不是自己手动拆分字符串。
  • 啊,你是对的。我通常不使用文件名,所以我不确定 Path 有什么方法。
猜你喜欢
  • 2012-02-15
  • 2013-06-01
  • 2020-06-22
  • 2014-08-12
  • 2013-10-24
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多