Click here to Skip to main content
Click here to Skip to main content

File renaming algorithm to mimic Windows copy+paste renaming

, 31 Aug 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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:  

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)

Share

About the Author

atamata
Web Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralMy vote of 4 PinmemberChristian Amado2-Sep-12 5:07 
Very Interesting!

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141015.1 | Last Updated 31 Aug 2012
Article Copyright 2012 by atamata
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid