Click here to Skip to main content
13,355,311 members (62,738 online)
Click here to Skip to main content
Add your own
alternative version


1 bookmarked
Posted 31 Aug 2012

File renaming algorithm to mimic Windows copy+paste renaming

, 31 Aug 2012
Rate this:
Please Sign up or sign in to vote.
File renaming algorith to mimic Windows copy+paste renaming


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

        '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
                CopyNumber = 1
                newfilename = CurrentFilename.Replace(fo.Extension, "") + _
                              " (" + CopyNumber.ToString + ")" + fo.Extension
            End If
            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

        Return CurrentFilename
    End If

End Function 


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


About the Author

Web Developer
United Kingdom United Kingdom
This member doesn't quite have enough reputation to be able to display their biography and homepage.

You may also be interested in...


Comments and Discussions

GeneralMy vote of 4 Pin
Christian Amado2-Sep-12 6:07
memberChristian Amado2-Sep-12 6: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 31 Aug 2012
Article Copyright 2012 by atamata
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid