簡體   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