title: How to Rename a Renamed file if already exist in asp.net?
body: <p>I am trying to rename files before moving to another subfolder. The first thing I do is to get the filenames and extensions of the files on the LOCATION FOLDER. After that I check whether those files exist on the ACTIVE FOLDER. If yes I renamed it by adding incremented integer. </p>
  
  <p>For instance LOCATION FOLDER contains 'sample.txt' file and ACTIVE FOLDER has no file like that. On that case I don't need to rename the file 'sample.txt', all I need to do is to move it to ACTIVE FOLDER. But when ACTIVE FOLDER contains such filename, when moved it must be renamed as sample(1).txt, and when another file on LOCATION FOLDER has filename 'sample.txt' when moved must be sample(2).txt.</p>
  
  <p>Below is my code</p>
  
  <pre><code>Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  
  
      Dim dir As New DirectoryInfo("C:\Documents and Settings\Admin\Desktop\LOCATION")
      Dim Folder1Files As FileInfo() = dir.GetFiles()
  
      For Each nFile As FileInfo In Folder1Files
  
          Dim fileName As String = Path.GetFileNameWithoutExtension(nFile.Name)
          Dim fileExt As String = Path.GetExtension(nFile.Name)
          Dim newFileName As String
          Dim fileNumber = 0
  
  
          If File.Exists("C:\Documents and Settings\Admin\Desktop\LOCATION\ACTIVE FOLDER\" &amp; fileName &amp; fileExt) Then
  
              fileNumber += 1
              newFileName = String.Format("{0}({1}){2}", fileName, fileNumber, fileExt)
  
  
              File.Move("C:\Documents and Settings\Admin\Desktop\LOCATION\" &amp; fileName &amp; fileExt, "C:\Documents and Settings\Admin\Desktop\LOCATION\ACTIVE FOLDER\" &amp; newFileName)
  
          Else
              File.Move("C:\Documents and Settings\Admin\Desktop\LOCATION\" &amp; fileName &amp; fileExt, "C:\Documents and Settings\Admin\Desktop\LOCATION\ACTIVE FOLDER\" &amp; fileName &amp; fileExt)
          End If
  
  
      Next
  
  
  End Sub
  </code></pre>
  
  <p>Whenever I tried to debug above code, and 'sample.txt' exist when moved it becomes 'sample(1).txt', therefore it's correct, but when 'sample.txt' exist again on LOCATION FOLDER when moved it becomes 'sample(1)(1).txt', where in fact it must be 'sample(2).txt'.</p>
  
  <p>What should I do to get my expected result?</p>
  
  <p>Thanks in advance.</p>