我正在尝试在VB中编写一个控制台应用程序,它允许我更改文件的名称。
我到目前为止的代码是:
Public Class Form1
Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
If txtpath.Text.Length <> 0 And txtName.Text.Length <> 0 Then
' Change "c:\test.txt" to the path and filename for the file that
' you want to rename.
' txtpath contains the full path for the file
' txtName contains the new name
My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)
Else
MessageBox.Show("Please Fill all Fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtpath.Clear()
txtName.Clear()
End Sub
End Class
但是当我尝试运行它时,我在这一行中收到错误:
My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)
有什么建议吗?
答案 0 :(得分:1)
改变:
My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)
要:
My.Computer.FileSystem.RenameFile(txtpath.Text.ToString, txtName.Text.ToString)
解决问题。
答案 1 :(得分:1)
问题是您在文本框对象上执行.ToString,而不是文本框的值。我总是检查以确保源文件和目标文件是否存在。此外,请确保将文件的完整路径传递给该函数以确保其正常运行。
尝试这样的事情:
If Not System.IO.File.Exists(txtpath.Text) Then
MsgBox("File not found!")
ElseIf System.IO.File.Exists(txtName.Text) Then
MsgBox("Target path already exists!")
Else
My.Computer.FileSystem.RenameFile(txtpath.Text, txtName.Text)
End If