简体   繁体   中英

VB Console application to rename a file

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?

Changing :

My.Computer.FileSystem.RenameFile(txtpath.ToString, txtName.ToString)

To:

My.Computer.FileSystem.RenameFile(txtpath.Text.ToString, txtName.Text.ToString)

Solves the Problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM