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

时间:2015-10-13 14:51:31

标签: .net vb.net file-move

下午好,

我正在尝试创建这个代码,允许我在目录中创建一个新文件夹,从我输入TextBox1.Text,然后打开一个对话框并选择一个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 Orders\98789'.       

-

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

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

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

谢谢,

斯蒂芬

2 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:0)

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

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

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