I understand how to rename a file in VB.NET as I use in the code at the end of my post. However, I was wondering if it's possible to rename a file and if the file exists then to rename it and add +1 to the file name?
So if I ran the code.
'Run it first time
My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")
'Run it again, but it should add +1 as the file will already exists, so it should be "c:\test\NewName1.txt"
My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")
Update
I decided rather than rename and +1, it would be better to just date stamp it, so for anyone who struggles as I did:
My.Computer.FileSystem.RenameFile("c:\test\test.txt", "Test" & Format(Date.Now, "ddMMyy") & ".txt")
Use the RenameFile method of the My. Computer. FileSystem object to rename a file by supplying the current location, file name, and the new file name. This method cannot be used to move a file; use the MoveFile method to move and rename the file.
You need to write your own logic for this.
The File
class has many useful method for dealing with files.
If File.Exists(filePath) Then
' Give a new name
Else
' Use existing name
End If
The Path
class has many methods for dealing with file paths.
Path.GetFileNameWithoutExtension(filePath)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With