3 Replies - 927 Views - Last Post: 06 May 2014 - 07:19 AM

#1 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1623
  • View blog
  • Posts: 5,200
  • Joined: 25-September 09

Rename a file if it exists in the destination

Posted 30 April 2014 - 08:02 AM

Today a question was asked about how to handle copying/moving a file to a destination that already exists, giving it a (#) to show a copy, so I started playing around with this.

Private Function RenameAsNeeded(dest As String) As String
        'Used to copy or move a file to a destination folder with the ability to rename as needed with a number
        'Set a variable to hold the number so that we can find the highest number for the file
        Dim x As Integer = 0
        Do Until Not IO.File.Exists(dest) 'Keep looping until the current build of the file does not exist
            x += 1
            'Remove the previous (#) sequence from the destination string
            'since x is being incremented, it will still check against the right filename
            dest = dest.Replace("(" & (x - 1).ToString & ").", ".")
            'All we're doing here is figuring out where the (#) goes, if it has an extension, we want it on the 
            'name, and add the extension back, otherwise, we just add it to the name.
            If dest.Contains(".") Then
                dest = dest.Split("."c)(0) & "(" & x & ")." & dest.Split("."c)(1)
            Else
                dest = dest & "(" & x & ")"
            End If
        Loop
        Return dest
        'Where I remove the previous (#). and replace it with . was so that if you had a filename like:
        'ThisIsMy(1)File.txt, the code should still work.
    End Function


To use this you would simply use the IO.File.Copy or IO.File.Move methods calling the function with the destination

IO.File.Copy("D:\AFileThatExists.txt", RenameAsNeeded("D:\Test\AFileThatExists.txt"))

So if AFileThatExists.txt already resides in D:\Test\ then the file is copied/moved as AFileThatExists(1).txt

Hopefully this helps someone. I haven't looked but since this occurs in Windows when you copy there is probably a method that exists but I didn't find one while searching.

This post has been edited by CharlieMay: 30 April 2014 - 08:22 AM


Is This A Good Question/Topic? 2
  • +

Replies To: Rename a file if it exists in the destination

#2 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3833
  • View blog
  • Posts: 13,580
  • Joined: 12-December 12

Re: Rename a file if it exists in the destination

Posted 30 April 2014 - 11:52 AM

View PostCharlieMay, on 30 April 2014 - 03:02 PM, said:

I haven't looked but since this occurs in Windows when you copy there is probably a method that exists but I didn't find one while searching.

I haven't found it either but I believe it does what Windows does, which is to create a file named "filename - Copy" and then "filename - Copy (2)".

I hope that you won't mind if I add an alternative approach that doesn't use Replace() or Split():
Imports System.IO

        Dim sOld As String = "C:\Users\Andrew\Documents\SampleText.txt"
        Dim sNew As String = "C:\Users\Andrew\Documents\ATextFile.txt"

        Dim sNewDir As String = Path.GetDirectoryName(sNew) & Path.DirectorySeparatorChar
        Dim sNewFile As String = Path.GetFileNameWithoutExtension(sNew)
        Dim sNewExtn As String = Path.GetExtension(sNew)
        Dim x As Integer = 0

        If File.Exists(sNew) Then
            Do
                x = x + 1
                sNew = sNewDir & sNewFile & CStr(x) & sNewExtn
            Loop While File.Exists(sNew)
        End If
        File.Copy(sOld, sNew)

This post has been edited by andrewsw: 30 April 2014 - 12:19 PM

Was This Post Helpful? 0
  • +
  • -

#3 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1623
  • View blog
  • Posts: 5,200
  • Joined: 25-September 09

Re: Rename a file if it exists in the destination

Posted 30 April 2014 - 12:00 PM

Nope, don't mind at all, I even found an example right after posting this that was much more elegant.
Was This Post Helpful? 0
  • +
  • -

#4 thava  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 180
  • View blog
  • Posts: 1,606
  • Joined: 17-April 07

Re: Rename a file if it exists in the destination

Posted 06 May 2014 - 07:19 AM

check out this one it doesn't loop through all the files in the folder
Private Sub CopyFile(oldfilename As String, NewFileName As String, Optional OverWrite As Boolean = True, Optional AppendNumber As Boolean = False)
        If OverWrite = True Then
            File.Copy(oldfilename, NewFileName, OverWrite)
        Else
            If File.Exists(NewFileName) AndAlso AppendNumber Then
                Dim Filename As String = Path.GetFileNameWithoutExtension(NewFileName)
                Dim DirName As String = Path.GetDirectoryName(NewFileName)
                Dim files As IEnumerable(Of String) = Directory.EnumerateFiles(DirName, Filename + "*", SearchOption.TopDirectoryOnly)
                Dim FileNumber = (From f In files Select (Getnumber(f))).Max
                Dim convertedFilename As String = Path.Combine(DirName, Filename + "-" + (FileNumber + 1).ToString("0") + Path.GetExtension(NewFileName))
                MsgBox(convertedFilename)
                File.Copy(oldfilename, convertedFilename)
            ElseIf Not File.Exists(NewFileName) Then
                File.Copy(oldfilename, NewFileName)
            Else
                System.Windows.Forms.MessageBox.Show("File Already Exists")
            End If
        End If
    End Sub
    Private Function Getnumber(FNM) As Integer
        Dim num As String
        FNM = Path.GetFileNameWithoutExtension(FNM)
        num = FNM.Substring(IIf(FNM.LastIndexOf("-") > 0, FNM.LastIndexOf("-") + 1, FNM.Length - 1))
        If IsNumeric(num) Then
            Return CInt(num)
        Else
            Return 0
        End If
    End Function


what ever the logic of the number you want put it in the Get number function

This post has been edited by thava: 06 May 2014 - 07:21 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1