Introduction
On a recent project I had to include functionality to write files to disk and needed to handle files with the same name. An easy way to do it would
have been to timestamp the filename, but I didn't like how messy that would look.
So I set about writing a file re-naming algorith which mimicked
the manner that windows renames files when you do a copy + paste. ie. when you copy + paste a file called 'Filename.txt' it calls it 'Filename - Copy.txt',
then if you paste it again it calls it 'Filename - Copy (1).txt'
I decided to leave out the ' - Copy' part of the filename for neatness and the following is the code to to achieve this.
The recursive nature of this function means that it will continue to call itself until it finds a filepath which does not already exist, this then will be the new filename.
Using the code
To use the function, simply pass in the path of the file as the Location
parameter, and the filename as the CurrentFilename
parameter.
The string returned will be the new unique filename.
Here's the code in VB:
Private Function GetNextFilename(ByVal Location As String, ByVal CurrentFilename As String) As String
If Not Location.EndsWith("\") Then Location = Location + "\"
If IO.File.Exists(Location + "\" + CurrentFilename) Then
Dim fo As New IO.FileInfo(Location + CurrentFilename)
Dim CopyNumber As Integer = Integer.MinValue
Dim newfilename As String = fo.Name.Replace(fo.Extension, "")
Dim obPos As Integer = newfilename.LastIndexOf("(")
Dim cbPos As Integer = newfilename.LastIndexOf(")")
If obPos > 0 AndAlso cbPos > 0 Then
If Integer.TryParse(Integer.Parse(newfilename.Substring(obPos + 1, _
cbPos - obPos - 1).ToString).ToString, CopyNumber) Then
CopyNumber += 1
newfilename = CurrentFilename.Replace(fo.Extension, "").Substring(0, obPos + 1) + _
CopyNumber.ToString + ")" + fo.Extension
Else
CopyNumber = 1
newfilename = CurrentFilename.Replace(fo.Extension, "") + _
" (" + CopyNumber.ToString + ")" + fo.Extension
End If
Else
CopyNumber = 1
newfilename = CurrentFilename.Replace(fo.Extension, "") + _
" (" + CopyNumber.ToString + ")" + fo.Extension
End If
While IO.File.Exists(Location + "\" + newfilename)
newfilename = GetNextFilename(Location, newfilename)
End While
Return newfilename
Else
Return CurrentFilename
End If
End Function