Private Function RenameAsNeeded(dest As String) As String 'Used to copy or move a file to a destination folder with the ability to rename as needed with a number 'Set a variable to hold the number so that we can find the highest number for the file Dim x As Integer = 0 Do Until Not IO.File.Exists(dest) 'Keep looping until the current build of the file does not exist x += 1 'Remove the previous (#) sequence from the destination string 'since x is being incremented, it will still check against the right filename dest = dest.Replace("(" & (x - 1).ToString & ").", ".") 'All we're doing here is figuring out where the (#) goes, if it has an extension, we want it on the 'name, and add the extension back, otherwise, we just add it to the name. If dest.Contains(".") Then dest = dest.Split("."c)(0) & "(" & x & ")." & dest.Split("."c)(1) Else dest = dest & "(" & x & ")" End If Loop Return dest 'Where I remove the previous (#). and replace it with . was so that if you had a filename like: 'ThisIsMy(1)File.txt, the code should still work. End Function
To use this you would simply use the IO.File.Copy or IO.File.Move methods calling the function with the destination
So if AFileThatExists.txt already resides in D:\Test\ then the file is copied/moved as AFileThatExists(1).txt
Hopefully this helps someone. I haven't looked but since this occurs in Windows when you copy there is probably a method that exists but I didn't find one while searching.
This post has been edited by CharlieMay: 30 April 2014 - 08:22 AM