Click here to Skip to main content
15,883,841 members
Articles / Programming Languages / Visual Basic
Tip/Trick

File renaming algorithm to mimic Windows copy+paste renaming

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
31 Aug 2012CPOL 12.5K   2   1
File renaming algorith to mimic Windows copy+paste renaming

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:  

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

        'we have filename without extension
        Dim newfilename As String = fo.Name.Replace(fo.Extension, "")
        'last index of the open bracket
        Dim obPos As Integer = newfilename.LastIndexOf("(")
        'last position of the closed bracket
        Dim cbPos As Integer = newfilename.LastIndexOf(")")

        'if both open and closed brackets are found
        If obPos > 0 AndAlso cbPos > 0 Then
            If Integer.TryParse(Integer.Parse(newfilename.Substring(obPos + 1, _
                                cbPos - obPos - 1).ToString).ToString, CopyNumber) Then
                'ok the parse was successful so increment the number
                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

        'ok now check if this new file exists
        While IO.File.Exists(Location + "\" + newfilename)
            'and if it does we'll call back into this function to get the next possible filename
            newfilename = GetNextFilename(Location, newfilename)
            'do this until we get a filename which doesn't exist
        End While

        Return newfilename

    Else
        Return CurrentFilename
    End If

End Function 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Christian Amado2-Sep-12 5:07
professionalChristian Amado2-Sep-12 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.