Jump to content

...


stuka
 Share

Recommended Posts

Let's say, I want to copy a file to another folder but it so happens that another file with the same name exist.

Is it possible to append a number or letter to the new file to enable a safe FileCopy to avoid overwriting?

If the 'File' detects 'File' then it is renamed 'File1'. If 'File1' detects 'File1' then it is then renamed 'File2' and so on...

Possible?

Yes
Link to comment
Share on other sites

Try it:

#include <File.au3>
Dim $source = "C:\test", $dest = "D:\temp", $var = 0, $count = 0
Global $FileArray

$FileArray = _FileListToArray($source, "*.*", 1)

For $i = 1 To $FileArray[0]
    If Not FileCopy($source & "\" & $FileArray[$i], $dest & "\") Then
        $path = $source & "\" & $FileArray[$i]
        $sSub = SubRout($path, $dest)
    EndIf
Next
MsgBox(64, "Done", $count & " files copyed")

Func SubRout($path, $dest)
    Local $szDrive, $szDir, $szFName, $szExt
    Local $sRet = "", $split = ""
    $split = _PathSplit($path, $szDrive, $szDir, $szFName, $szExt)
    If FileCopy($path, $dest & "\" & $szFName & $var & $szExt) Then
        $count += 1
        $var = 0
    Else
        $var += 1
        $sRet = SubRout($path, $dest)
    EndIf
EndFunc
Link to comment
Share on other sites

Different take on it, (just don't use destination filename with more than one period):

FileWrite ("New Text document.txt", "")

_IncrementalFileCopy("New Text document.txt", "New Text document.txt")

Func _IncrementalFileCopy($Source, $Destination)
    $count = 0
    
    Do
        ;Split destination into file / extension
        $pathArray = StringSplit ( $Destination, ".")
        
        ;If more than one period in destination filename, return error
        if $pathArray[0] > 2 then return 3
            
        $newDestination = $pathArray[1] & $count & "." & $pathArray[2]
        $count += 1
    Until FileExists($newDestination) = 0
    
    ;Copy file without overwrite just to be safe
    FileCopy ( $Source, $newDestination, 8)
    
    Return @error
EndFunc
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...