Trouble Renaming File with Textbox input
I have been struggling a bit trying to get this to work. I am trying to rename the file but can't seem to get it to work. The file creates but just doesn't seem to rename with the text in the text box. Any ideas to point me in the right direction would be great. Below is the code.
Code to generate File Code:
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
If File.Exists("c:\Sample.txt") Then
'shows message if testFile exist
MsgBox("File Already Exist ")
Else
'create the file testFile.txt
File.Create("c:\Sample.txt")
MsgBox("File Has Been Created ")
End If
End Sub
Code to Rename File Code:
Public Sub RenameFile()
Dim mOldFilePath As String = "C:\Sample.txt"
'Dim mExtension As String
Dim mNewFileName As String
mNewFileName = txtName.Text
My.Computer.FileSystem.RenameFile(mOldFilePath, mNewFileName)
Thanks in Advance
RCA20
Re: Trouble Renaming File with Textbox input
Why create the file and then rename it? Why not just create it with the correct name in the first place?
As for the issue, File.Create doesn't just create a file. It also opens it and returns a FileStream with which you can write to the file. You won't be able to rename, delete, etc, that file until that FileStream is closed.
Re: Trouble Renaming File with Textbox input
this allows you to change the filename and the extension
vb Code:
Public Sub RenameFile()
Dim mOldFilePath As String = "C:\Sample.txt"
Dim mOldFileName As String = IO.Path.GetFileNameWithoutExtension(mOldFilePath)
Dim mOldExtension As String = IO.Path.GetExtension(mOldFilePath)
Dim mNewFileName As String = IO.Path.GetFileNameWithoutExtension(txtName.Text)
Dim mNewExtension As String = If(IO.Path.GetExtension(txtName.Text) <> "", IO.Path.GetExtension(txtName.Text), mOldExtension)
My.Computer.FileSystem.RenameFile(mOldFilePath, mOldFilePath.replace(mOldFileName & mOldExtension, mNewFileName & mNewExtension)))
end sub
1 Attachment(s)
Re: Trouble Renaming File with Textbox input
Paul thanks for your help. After playing with the code I still haven't been able to get it too work.
jmcilhinney you may be right but I just couldn't figure out any other way to do it. Being new to this I thought I had to create the file first then write to that file. Problem was that the user gets too save the file name at runtime.
Example
Attachment 75554
The goal was to allow the user to save the text that was generate in a richtextbox from a different form to the specific folder and name that file. Maybe I am going about it all the wrong way and considering I am new too this I wouldn't doubt it.
Re: Trouble Renaming File with Textbox input
Just store the file path selected by the user in a String variable. When it comes time write your text to the file you simply call File.WriteAllText or whatever and specify the file path using that variable.