繁体   English   中英

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

[英]VB Console application to rename a file

我试图在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)

有什么建议么?

改变:

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

至:

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

解决问题。

问题是您在文本框对象上执行.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

暂无
暂无

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

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