How to increment the filename if file already exists

12,352

Solution 1

Hi here's a pretty "procedural" answer:

Dim counter As Integer = 0

Dim newFileName As String = orginialFileName

While File.Exists(newFileName)
    counter = counter + 1
    newFileName = String.Format("{0}({1}", orginialFileName, counter.ToString())
End While

you will need an imports statement for System.IO

Solution 2

The above procedure add the counter at the end, but i my case a want to keep the extention of the file, so i have expanded the function to this:

Public Shared Function FileExistIncrementer(ByVal OrginialFileName As String) As String
    Dim counter As Integer = 0
    Dim NewFileName As String = OrginialFileName
    While File.Exists(NewFileName)
        counter = counter + 1
        NewFileName = String.Format("{0}\{1}-{2}{3}", Path.GetDirectoryName(OrginialFileName), Path.GetFileNameWithoutExtension(OrginialFileName), counter.ToString(), Path.GetExtension(OrginialFileName))
    End While
    Return NewFileName
End Function
Share:
12,352
Ram
Author by

Ram

Updated on August 25, 2022

Comments

  • Ram
    Ram over 1 year

    In my vb.net winform application, I am moving the file (ex: sample.xls from one folder to another. If file already exists with the same name, the new file name should be incremented (ex:sample(1).xls). How can i acheive this?

  • MrJD
    MrJD over 11 years
    Not a good solution if there are millions of files with the same name, for instance an image sequence.