Visual Studio 2013 - 将文件移动到另一个路径

Visual Studio 2013 - Move File To Another Path

大家下午好,

我正在尝试创建这段代码,它允许我在我输入 TextBox1.Text 的目录中创建一个新文件夹,然后打开一个对话框和 select 一个 PDF,它将然后将文件路径放入TextBox2(同样适用于TextBox3中的单独PDF)。

An unhandled exception of type 'System.IO.IOException' occurred in Microsoft.VisualBasic.dll

Additional information: Could not complete operation since a directory already exists in this path '\ANVILSRV\Public\Completed Works Orders789'.       

-

这是我在尝试完成操作时遇到的错误,它会创建文件夹但不会移动任何文件。

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

    Dim txt As String
    txt = TextBox1.Text

    If My.Computer.FileSystem.DirectoryExists("\ANVILSRV\Public\Completed Works Orders\" & txt & "") Then

        MsgBox("Could not create the folder " & txt & " because it already exists.")

    Else

        My.Computer.FileSystem.CreateDirectory("\ANVILSRV\Public\Completed Works Orders\" & txt & "")

        My.Computer.FileSystem.MoveFile(TextBox2.Text, ("\ANVILSRV\Public\Completed Works Orders\" & txt & ""), True)

        My.Computer.FileSystem.MoveFile(TextBox3.Text, ("\ANVILSRV\Public\Completed Works Orders\" & txt & ""), True)

    End If

End Sub

非常感谢任何建议或帮助。

谢谢,

斯蒂芬

移动文件语法需要以下参数

sourceFileName = 源文件的完整路径

destinationFileName = 目标文件的完整路径

overWrite = 布尔值,如果目标文件已经存在,是否覆盖

FileSystem.MoveFile(sourceFileName As String, destinationFileName As String, overWrite As Boolean)

在您的代码中,您没有为参数 destinationFileName 提供完整的文件路径,而是指定了文件夹路径。在您的代码中提供完整的文件名,它将起作用。例如"C:\Windows\DirectX.txt"

试试下面的代码

My.Computer.FileSystem.MoveFile(TextBox2.Text, ("\ANVILSRV\Public\Completed Works Orders\" & txt & "\" & fileName), True)

我建议将您在代码中重复使用几次的路径更改为常量。

此外,不需要所有路径字符串末尾的 ""。这就是我的意思(我只是做了一个快速测试,所以我没有包括所有内容,但你可以从中得到这个想法;我测试了以下代码并且它有效):

Const path As String = "\ANVILSRV\Public\Completed Works Orders\"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim txt As String
    txt = TextBox1.Text

    If My.Computer.FileSystem.DirectoryExists(path & txt) Then
        MsgBox("Could not create the folder " & txt & " because it already exists.")
    Else
        My.Computer.FileSystem.CreateDirectory(path & txt)
    End If
End Sub