Jump to content
Sign in to follow this  
JohnOne

_FileRename

Recommended Posts

JohnOne

;===================================================================================================
;
; function Name:    _FileRename
; Description:      renames a file 
; Parameter(s):     $sFile = Full path to file ("c:pathtofile.ext") 
;                   $sRename = New Filename ("newname.ext") 
;                   $iOverWrite = 0 or 1 (1 overwrite new filename if exists, 0 do not overwrite) 
; Return Value(s):
;                 On Success:
;                   returns 1 
;                 On Failure:
;                   returns 0 
;                 @Error:
;                   1 if function fails 
;                 @Extended:
;                   1 if new filename exist before rename 
;                   0 if new filename not exist before rename 
; Remark(s):      http://www.autoitscript.com/forum/topic/146088-filerename/ 
; Author(s):      JohnOne 
;
;===================================================================================================

$File = @ScriptDir & 'filetorename.txt'
FileWrite($File, 'Test')
_FileRename($File, 'newname.txt')
If @error Then MsgBox(0, "Error", @error)

Func _FileRename($sFile, $sRename, $iOverWrite = 0)
    Local Const $FILENOTEXIST = 2
    If Not FileExists($sFile) Then Return SetError($FILENOTEXIST, 0, 0)
    Local $_StringLen = StringLen($sFile)
    Local $_StringInStr = StringInStr($sFile, "", 0, -1, $_StringLen)
    Local $_Dir = StringLeft($sFile, $_StringInStr)
    Local $_NewFile = $_Dir & $sRename
    Local $_NewFileExists = FileExists($_NewFile)
    Local $_FileMove = FileMove($sFile, $_NewFile, $iOverWrite)
    Return SetError(Not $_FileMove, $_NewFileExists, $_FileMove)
EndFunc   ;==>_FileRename

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites
guinness

Nice idea. As you're probably aware $_FileName isn't being used.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
guinness

You're using $File in the function, but I presume this should be $sFile?


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
JohnOne

I added this method to wiki a while back and forgot to update this thread.

FileRename(@ScriptDir & "\rename.txt", @ScriptDir & "\renamed.txt")

Func FileRename($FileName, $ReName)

    Local $SHFILEOPSTRUCT, $SourceStruct, $DestStruct
    Local Const $FO_RENAME = 0x0004
    Local Const $FOF_SILENT = 0x0004
    Local Const $FOF_NOCONFIRMATION = 0x0010
    Local Const $FOF_NOERRORUI = 0x0400
    Local Const $FOF_NOCONFIRMMKDIR = 0x0200
    Local Const $NULL = 0

    $SourceStruct = _StringToStruct($FileName)
    $DestStruct = _StringToStruct($ReName)

    $SHFILEOPSTRUCT = DllStructCreate( _
    "hwnd hWnd;" & _
    "uint wFunc;" & _
    "ptr pFrom;" & _
    "ptr pTo;" & _
    "int fFlags;" & _
    "int fAnyOperationsAborted;" & _
    "ptr hNameMappings;" & _
    "ptr lpszProgressTitle")

    DllStructSetData($SHFILEOPSTRUCT, "hWnd", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "wFunc", $FO_RENAME)
    DllStructSetData($SHFILEOPSTRUCT, "pFrom", DllStructGetPtr($SourceStruct))
    DllStructSetData($SHFILEOPSTRUCT, "pTo", DllStructGetPtr($DestStruct))
    DllStructSetData($SHFILEOPSTRUCT, "fFlags", BitOR($FOF_SILENT, $FOF_NOCONFIRMATION, $FOF_NOERRORUI, $FOF_NOCONFIRMMKDIR))
    DllStructSetData($SHFILEOPSTRUCT, "fAnyOperationsAborted", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "hNameMappings", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "lpszProgressTitle", $NULL)

    $acall = DllCall("shell32.dll", "int", "SHFileOperation", "ptr", DllStructGetPtr($SHFILEOPSTRUCT))
    If @error Then
        Return SetError(@error, @extended, 0)
    EndIf
    Return 1
EndFunc   ;==>FileRename

Func _StringToStruct($string)

    Local $iLen = StringLen($string)
    Local $Struct = DllStructCreate("char[" & String($iLen + 2) & "]")
    DllStructSetData($Struct, 1, $string)
    DllStructSetData($Struct, 1, 0, $iLen + 1)
    DllStructSetData($Struct, 1, 0, $iLen + 2)

    Return $Struct
EndFunc   ;==>_StringToStruct
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites
Jury

Yes great! this works for me unlike your first function posted in this topic (I get error = 1) wish this one you posted on wiki had the $iOverWrite  option though.

Thanks

Edited by Jury

Share this post


Link to post
Share on other sites
JohnOne

FileRename(@ScriptDir & "\rename.txt", @ScriptDir & "\renamed.txt", 0)

Func FileRename($FileName, $ReName, $iOverWrite = 1)

    Local $SHFILEOPSTRUCT, $SourceStruct, $DestStruct
    Local Const $FO_RENAME = 0x0004
    Local Const $FOF_SILENT = 0x0004
    Local Const $FOF_NOCONFIRMATION = 0x0010
    Local Const $FOF_NOERRORUI = 0x0400
    Local Const $FOF_NOCONFIRMMKDIR = 0x0200
    Local Const $NULL = 0
    Local Const $FILENAMENOTEXISTS = 6
    Local Const $RENAMEEXISTS = 7

    If Not FileExists($FileName) Then
        Return SetError($FILENAMENOTEXISTS, 0, 0)
    EndIf
    If FileExists($ReName) And Not $iOverWrite Then
        Return SetError($RENAMEEXISTS, 0, 0)
    EndIf

    $SourceStruct = _StringToStruct($FileName)
    $DestStruct = _StringToStruct($ReName)

    $SHFILEOPSTRUCT = DllStructCreate( _
            "hwnd hWnd;" & _
            "uint wFunc;" & _
            "ptr pFrom;" & _
            "ptr pTo;" & _
            "int fFlags;" & _
            "int fAnyOperationsAborted;" & _
            "ptr hNameMappings;" & _
            "ptr lpszProgressTitle")

    DllStructSetData($SHFILEOPSTRUCT, "hWnd", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "wFunc", $FO_RENAME)
    DllStructSetData($SHFILEOPSTRUCT, "pFrom", DllStructGetPtr($SourceStruct))
    DllStructSetData($SHFILEOPSTRUCT, "pTo", DllStructGetPtr($DestStruct))
    DllStructSetData($SHFILEOPSTRUCT, "fFlags", BitOR($FOF_SILENT, $FOF_NOCONFIRMATION, $FOF_NOERRORUI, $FOF_NOCONFIRMMKDIR))
    DllStructSetData($SHFILEOPSTRUCT, "fAnyOperationsAborted", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "hNameMappings", $NULL)
    DllStructSetData($SHFILEOPSTRUCT, "lpszProgressTitle", $NULL)

    $acall = DllCall("shell32.dll", "int", "SHFileOperation", "ptr", DllStructGetPtr($SHFILEOPSTRUCT))
    If @error Then
        Return SetError(@error, @extended, 0)
    EndIf
    Return 1
EndFunc   ;==>FileRename

Func _StringToStruct($string)

    Local $iLen = StringLen($string)
    Local $Struct = DllStructCreate("char[" & String($iLen + 2) & "]")
    DllStructSetData($Struct, 1, $string)
    DllStructSetData($Struct, 1, 0, $iLen + 1)
    DllStructSetData($Struct, 1, 0, $iLen + 2)

    Return $Struct
EndFunc   ;==>_StringToStruct

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites
Jury

Thanks John_One

Share this post


Link to post
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
Sign in to follow this  

×