Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename files in VB.NET to have a unique suffix?

Tags:

.net

vb.net

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")
like image 719
JackSparrow Avatar asked May 28 '12 12:05

JackSparrow


People also ask

How do I rename a file in VB NET?

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.


1 Answers

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)
like image 63
Oded Avatar answered Nov 15 '22 09:11

Oded