Hello All

I'm new to VB and i need help on how to rename text file with textbox contents. I have a textbox and i would like to make it so once a button is clicked the text file is renamed according to the contents in the textbox.

I am using VB 2008.

Can you help me please?

Thankyou
Aram

Hi aram25
To rename a file, use the fileinfo.move method. Something like this:

Private Sub RenameFile(ByVal Path As String, ByVal NewName As String)
        Dim fInfo As FileInfo = Nothing
        Try
            fInfo = New FileInfo(Path)
            Try
                fInfo.MoveTo(fInfo.DirectoryName & NewName)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Assuming you know the full path of the file whose name you wish to change, you can then place a button and a textbox on a form and place the following code in the button click event:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RenameFile(KnownFilePath, TextBox1.Text)
    End Sub

Hi crapulency

Thanks for your help

I tried to use the second bit of code you provided but it came up with an error saying 'rename file not declared'

I then came across this code for renaming files:

My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")

i adapted it so it would use the textbox contents:

My.Computer.FileSystem.RenameFile("C:\order.txt", custoname.Text)

but when order.txt is renamed the ".txt" of the file is discarded making the file unreadable

can you help me with this please. your help would be greatly appreciated

Thanks
Aram

Well you learn something new everyday, don't you! I wasn't aware of this function, but it would seem to do the same as the one I provided. May as well use it as it comes built in.

Try something like this (a form with textbox and button):

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim sNewName As String = custoname.Text
        If sNewName = String.Empty Then
            MsgBox("You must enter a new filename")
        Else
            If Not (sNewName.EndsWith(".txt")) Then
                sNewName &= ".txt"
            End If
            My.Computer.FileSystem.RenameFile("C:\order.txt", sNewName)
        End If
    End Sub
End Class

Thankyou crapulency for your help, my problem is now solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.