【问题标题】:Visual Studio 2013 - Move File To Another PathVisual Studio 2013 - 将文件移动到另一个路径
【发布时间】:2015-10-13 14:51:31
【问题描述】:

大家下午好,

我正在尝试创建此代码,该代码将允许我从输入到 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

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

谢谢,

斯蒂芬

【问题讨论】:

  • 我认为 TextBox1 和 2 需要完全限定的路径。如果目录已经存在,则奇怪的“附加信息”消息,因为 CreateDirectory() 不会引发错误。检查是否存在可能是一种好习惯,但不是必需的。文档声明 IOException 错误与权限有关,而不是存在。如果 from 路径不是完全限定的,则会导致 IOException。
  • 我想我看到了问题 - from 和 to 应该是完全合格的filenames。 To 不是文件夹,而是完全限定的路径。

标签: .net vb.net file-move


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

【讨论】:

    【解决方案2】:

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多