Quote Originally Posted by MattP View Post
An alternative to jmcilhinney's solution getting an array of files matching the file name and extension and checking against that rather than hitting the file system each time to check if a file exists.

vb.net Code:
  1. Private Function GetUniqueFileName(filePath As String) As String
  2.         Dim folderName = Path.GetDirectoryName(filePath)
  3.         Dim fileName = Path.GetFileNameWithoutExtension(filePath)
  4.         Dim extension = Path.GetExtension(filePath)
  5.  
  6.         Dim fileNames = Directory.GetFiles(folderName, fileName & "*" & extension)
  7.         Dim fileNumber = 1
  8.  
  9.         If fileNames.Contains(filePath) Then
  10.             Do
  11.                 filePath = Path.Combine(folderName, String.Format("{0} ({1}){2}",
  12.                                                                   fileName,
  13.                                                                   fileNumber,
  14.                                                                   extension))
  15.                 fileNumber += 1
  16.             Loop While fileNames.Contains(filePath)
  17.         End If
  18.  
  19.         Return filePath
  20.     End Function
While it's not really a big deal, only one of those five declared variables is used unless you enter the If block so the other four really belong inside the If block too.