Reputation: 480
I am trying to write a Console Application in VB that will allow me to change the name of a file.
The code I have so far is:
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
But when I try to run it i get an error in this line:
My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)
Any suggestions?
Upvotes: 0
Views: 633
Reputation: 1857
The problem is that you are performing .ToString on the textbox object, and not the value of the textbox. I always check to make sure that the source and destination files exist or not. Also, make sure that you are passing the full path to the files to that function to ensure it performs properly.
Try something like this:
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
Upvotes: 1
Reputation: 480
Changing :
My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)
To:
My.Computer.FileSystem.RenameFile(txtpath.Text.ToString, txtName.Text.ToString)
Solves the Problem.
Upvotes: 1