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

.net, vb.net

Solution

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)

Problem

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") ```

Original source