Search code examples
vb.netsavefile-exists

File.Exists Is Not Adding File Number to Existing File in Directory Before Saving


I'm trying to check if the file exists in the directory in which the application was saved and if so, to add a number at the end -1, -2. -3 - based on whether a file with the same name already exists. My code is below:

 Dim FileName, FilePath As String
 Dim FileNumber As Integer

 FileName = ProjectName 
 FilePath = Path.Combine(CurrentDirectory, FileName)

 If File.Exists(FilePath) = True Then
    Do While File.Exists(FilePath)
          FileNumber = FileNumber + 1
          FileName = FileName & "-" & FileNumber
          FilePath = Path.Combine(CurrentDirectory, FileName)
    Loop
  End If

  NewWorkbook.SaveAs(FilePath)

When I run this code and the file is saving the first time, it works as intended but if I try saving the file with the same name a second time, there is no iterated FileNumber added to it, so the file name stays the same and it cannot save without replacing the original file.

Why is the File.Exists not recognizing that this file already exists and how can I fix this?


Solution

  • There is a logical problem in your code. You continue to modify the same variable and building continuosly new names.
    For example. Suppose to have initially a file with the name "Project.vb". At the first iteration inside the loop you check for a file named "Project.vb1", if your loop continues at the second iteration you check for a file named "Project.vb12" and so on.

    A more correct way could be

    Dim FileName, FileWithoutExtension, FileExtension, FilePath As String
    Dim FileNumber As Integer = 1
    Dim currentDirectory As String = "E:\temp" ' as an example
    FileName = "test.txt"                      ' as an example
    
    FileExtension = Path.GetExtension(FileName)
    FileWithoutExtension = Path.GetFileNameWithoutExtension(FileName)
    FilePath = Path.Combine(CurrentDirectory, FileName)
    
    ' No need of additional if to test file existance.
    Do While File.Exists(FilePath)
        FileNumber = FileNumber + 1
        ' Rebuild the Filename part wtih all the info
        FileName = FileWithoutExtension & "-" & FileNumber.ToString("D3") + FileExtension
        FilePath = Path.Combine(CurrentDirectory, FileName)
    Loop
    NewWorkbook.SaveAs(FilePath)