How to increase file name if file already exists

In my winform vb.net application, I move the file (for example: sample.xls from one folder to another. If the file already exists with the same name, the new file name should be increased (for example: sample (1)). Xls). How can I understand that?

+3
source share
2 answers

Hi here is 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 import statement for System.IO

+8
source

The above procedure adds a counter to the end, but in my case you want to save the file extension, so I 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
+5
source

All Articles