简体   繁体   English

用于重命名文件的VB控制台应用程序

[英]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. 我试图在VB中编写一个控制台应用程序,它允许我更改文件的名称。

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. 问题是您在文本框对象上执行.ToString,而不是文本框的值。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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