Jump to content
Sign in to follow this  
Innovative

[Func] FileRename

Recommended Posts

Innovative

I've seen some filerename functions but those functions are using FileMove command.. I've tried FileMove before but to me, it takes a long time to finish the command for a big size files..

This command wont be using FileMove command therefore speeding up the rename process..

Source :

#include <Process.au3>
#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.2.10.0
 Author:         xVivoCity (Xandaire Productions - http://xandaire.no-ip.org)

 Script Function:
    FileRename($fr_FullPath, $fr_RenamePath)
    
    $fr_Fullpath - The full path of the target rename FileChangeDir
    $fr_NewName - New name WITH the file type
    
    Example :
    
    FileRename(@desktopdir & "\File.htm", "NewFile.htm")
    
    Please keep the copyright intact if you are going to use this as a include.

#ce ----------------------------------------------------------------------------

Func FileRename($fr_FullPath, $fr_Rename)
    If $fr_Fullpath = "" Then
        Return -1
    Elseif $fr_Rename = "" Then
        Return -1
    Else
        _RunDOS("ren """& $fr_FullPath &""" """& $fr_Rename &"""")
        Return 1
    EndIf
    
        
Endfunc

Downloads :

FileRename.au3

FileRename_Example.au3

Share this post


Link to post
Share on other sites
Innovative

Now i realise why people always say something like

OMG, 55 views and no reply.

Share this post


Link to post
Share on other sites
JellyFish666

smart idea to rename a file, knew about the command but would of never thought of doing that.

Edited by JellyFish666

Share this post


Link to post
Share on other sites
GtaSpider

I think this is smarter:

_FileRename("d:\wg\test.txt","test123.exe")
Func _FileRename($sFile,$sRenameName)
    If NOt FileExists($sFile) Then Return SetError(1,0,-1)
    Local $sDir = StringLeft($sFile,StringInStr($sFile,"\",0,-1))
    FileMove($sFile,$sDir&$sRenameName)
    If @error Then Return SetError(2,@error,-1)
EndFunc

spider


www.AutoIt.de - Moderator of theĀ German AutoIt Froum

Share this post


Link to post
Share on other sites
Innovative

I think this is smarter:

_FileRename("d:\wg\test.txt","test123.exe")
Func _FileRename($sFile,$sRenameName)
    If NOt FileExists($sFile) Then Return SetError(1,0,-1)
    Local $sDir = StringLeft($sFile,StringInStr($sFile,"\",0,-1))
    FileMove($sFile,$sDir&$sRenameName)
    If @error Then Return SetError(2,@error,-1)
EndFunc

spider

Didn't i say it in my first post? FileMove takes a long time to move a huge file for me.

Share this post


Link to post
Share on other sites
JellyFish666

even better

Func FileRename($fr_FullPath, $fr_Rename)
    If $fr_Fullpath = "" Then
        Return -1
    ElseIf $fr_Rename = "" Then
        Return -1
    ElseIf Not FileExists($fr_Fullpath) Then
        Return -1
    Else
        _RunDOS("ren """& $fr_FullPath &""" """& $fr_Rename &"""")
        Return 1
    EndIf
Endfunc

Share this post


Link to post
Share on other sites
flip209

FYI the process.au3 includes all of this:

; Include Version:1.59  (04/20/2006)
#include-once
; ------------------------------------------------------------------------------
;
; AutoIt Version: 3.0
; Language:       English
; Description:    Functions that assist with process management.
;
; ------------------------------------------------------------------------------

;===============================================================================
;
; Description -   Returns a string containing the process name that belongs to a given PID.
; Syntax -        _ProcessGetName( $iPID )
; Parameters -    $iPID - The PID of a currently running process
; Requirements -  None.
; Return Values - Success - The name of the process
;                 Failure - Blank string and sets @error
;                       1 - Process doesn't exist
;                       2 - Error getting process list
;                       3 - No processes found
; Author(s) -     Erifash <erifash [at] gmail [dot] com>, Wouter van Kesteren.
; Notes -         Supplementary to ProcessExists().
;===============================================================================
Func _ProcessGetName($i_PID)
    If Not ProcessExists($i_PID) Then
        SetError(1)
        Return ''
    EndIf
    Local $a_Processes = ProcessList()
    If Not @error Then
        For $i = 1 To $a_Processes[0][0]
            If $a_Processes[$i][1] = $i_PID Then Return $a_Processes[$i][0]
        Next
    EndIf
    SetError(1)
    Return ''
EndFunc   ;==>_ProcessGetName

;===============================================================================
;
; Function Name:    _ProcessGetPriority()
; Description:      Get the  priority of an open process
; Parameter(s):     $vProcess      - PID or name of a process.
; Requirement(s):   AutoIt Beta v3.1.1.61+
;                   kernel32.dll (included with Windows)
; Return Value(s):  On Success - Returns integer corressponding to
;                   the processes's priority:
;                     0 - Idle/Low
;                     1 - Below Normal (Not supported on Windows 95/98/ME)
;                     2 - Normal
;                     3 - Above Normal (Not supported on Windows 95/98/ME)
;                     4 - High
;                     5 - Realtime
; On Failure:       Returns -1 and sets @Error to 1
; Author(s):        Matthew Tucker
;                   Valik added Pid or Processname logic
;===============================================================================
;
Func _ProcessGetPriority($vProcess)
    Local $i_PID = ProcessExists($vProcess)
    If Not $i_PID Then
        SetError(1)
        Return -1
    EndIf
    Local $hDLL = DllOpen('kernel32.dll')
    Local $aProcessHandle = DllCall($hDLL, 'int', 'OpenProcess', 'int', 0x0400, 'int', False, 'int', $i_PID)
    Local $aPriority = DllCall($hDLL, 'int', 'GetPriorityClass', 'int', $aProcessHandle[0])
    DllCall($hDLL, 'int', 'CloseHandle', 'int', $aProcessHandle[0])
    DllClose($hDLL)
    Switch $aPriority[0]
        Case 0x00000040
            Return 0
        Case 0x00004000
            Return 1
        Case 0x00000020
            Return 2
        Case 0x00008000
            Return 3
        Case 0x00000080
            Return 4
        Case 0x00000100
            Return 5
        Case Else
            SetError(1)
            Return -1
    EndSwitch

EndFunc   ;==>_ProcessGetPriority

;===============================================================================
;
; Description:      Executes a DOS command in a hidden command window.
; Syntax:           _RunDOS( $sCommand )
; Parameter(s):     $sCommand - Command to execute
; Requirement(s):   None
; Return Value(s):  On Success - Returns the exit code of the command
;                   On Failure - Depends on RunErrorsFatal setting
; Author(s):        Jeremy Landes <jlandes at landeserve dot com>
; Note(s):          None
;
;===============================================================================
Func _RunDOS($sCommand)
    Return RunWait(@ComSpec & " /C " & $sCommand, "", @SW_HIDE)
EndFunc   ;==>_RunDOS
Edited by flip209

" I haven't failed. I've just found 10,000 ways that won't work." Thomas Edison "You cannot help men permanently by doing for them what they could and should do for themselves." Abraham Lincoln

Share this post


Link to post
Share on other sites
Innovative

FYI the process.au3 includes all of this:

; Include Version:1.59  (04/20/2006)
#include-once
; ------------------------------------------------------------------------------
;
; AutoIt Version: 3.0
; Language:       English
; Description:    Functions that assist with process management.
;
; ------------------------------------------------------------------------------

;===============================================================================
;
; Description -   Returns a string containing the process name that belongs to a given PID.
; Syntax -        _ProcessGetName( $iPID )
; Parameters -    $iPID - The PID of a currently running process
; Requirements -  None.
; Return Values - Success - The name of the process
;                 Failure - Blank string and sets @error
;                       1 - Process doesn't exist
;                       2 - Error getting process list
;                       3 - No processes found
; Author(s) -     Erifash <erifash [at] gmail [dot] com>, Wouter van Kesteren.
; Notes -         Supplementary to ProcessExists().
;===============================================================================
Func _ProcessGetName($i_PID)
    If Not ProcessExists($i_PID) Then
        SetError(1)
        Return ''
    EndIf
    Local $a_Processes = ProcessList()
    If Not @error Then
        For $i = 1 To $a_Processes[0][0]
            If $a_Processes[$i][1] = $i_PID Then Return $a_Processes[$i][0]
        Next
    EndIf
    SetError(1)
    Return ''
EndFunc   ;==>_ProcessGetName

;===============================================================================
;
; Function Name:    _ProcessGetPriority()
; Description:      Get the  priority of an open process
; Parameter(s):     $vProcess      - PID or name of a process.
; Requirement(s):   AutoIt Beta v3.1.1.61+
;                   kernel32.dll (included with Windows)
; Return Value(s):  On Success - Returns integer corressponding to
;                   the processes's priority:
;                     0 - Idle/Low
;                     1 - Below Normal (Not supported on Windows 95/98/ME)
;                     2 - Normal
;                     3 - Above Normal (Not supported on Windows 95/98/ME)
;                     4 - High
;                     5 - Realtime
; On Failure:       Returns -1 and sets @Error to 1
; Author(s):        Matthew Tucker
;                   Valik added Pid or Processname logic
;===============================================================================
;
Func _ProcessGetPriority($vProcess)
    Local $i_PID = ProcessExists($vProcess)
    If Not $i_PID Then
        SetError(1)
        Return -1
    EndIf
    Local $hDLL = DllOpen('kernel32.dll')
    Local $aProcessHandle = DllCall($hDLL, 'int', 'OpenProcess', 'int', 0x0400, 'int', False, 'int', $i_PID)
    Local $aPriority = DllCall($hDLL, 'int', 'GetPriorityClass', 'int', $aProcessHandle[0])
    DllCall($hDLL, 'int', 'CloseHandle', 'int', $aProcessHandle[0])
    DllClose($hDLL)
    Switch $aPriority[0]
        Case 0x00000040
            Return 0
        Case 0x00004000
            Return 1
        Case 0x00000020
            Return 2
        Case 0x00008000
            Return 3
        Case 0x00000080
            Return 4
        Case 0x00000100
            Return 5
        Case Else
            SetError(1)
            Return -1
    EndSwitch

EndFunc   ;==>_ProcessGetPriority

;===============================================================================
;
; Description:      Executes a DOS command in a hidden command window.
; Syntax:           _RunDOS( $sCommand )
; Parameter(s):     $sCommand - Command to execute
; Requirement(s):   None
; Return Value(s):  On Success - Returns the exit code of the command
;                   On Failure - Depends on RunErrorsFatal setting
; Author(s):        Jeremy Landes <jlandes at landeserve dot com>
; Note(s):          None
;
;===============================================================================
Func _RunDOS($sCommand)
    Return RunWait(@ComSpec & " /C " & $sCommand, "", @SW_HIDE)
EndFunc   ;==>_RunDOS
I do know that.. and why ?

Share this post


Link to post
Share on other sites
litlmike

I am gonna submit this to GaryFrost for inclusion. Here is package:

"attachment=21489:_FileRename.zip" -Removed 07-29-2008 @ 8:57 AM PST

Edited by litlmike

Share this post


Link to post
Share on other sites
Gigglestick

Just curious if anyone's thought of testing the exit code of the ren command for errors, or does it even return one?

In some quick tests with renaming, when I get "Access is denied." for permissions issues, the exit code is 1, so perhaps a quick check of the exit code would help to return a more precise status of the result.

Something like...

Func FileRename($fr_FullPath, $fr_Rename)
    If $fr_Fullpath = "" Then
        Return -1
    ElseIf $fr_Rename = "" Then
        Return -1
    ElseIf Not FileExists($fr_Fullpath) Then
        Return -1
    Else
       ; Return the exitcode returned by the command
        Return _RunDOS("ren """& $fr_FullPath &""" """& $fr_Rename &"""")
    EndIf
Endfunc

I was looking at Run to see if it was feasible to capture the output of the command, but it doesn't look like it's possible to capture the exitcode of the command also when using Run. I'd like to suggest a change to the RunWait command to be able to attach StdOut and StdErr like the Run command so you could do a StdOutRead and StdErrRead to get the actual result of the command, while RunWait continues to return the actual exitcode of the command. In this example, you could then see what the errors were ("Access is denied.").


My UDFs: ExitCodes

Share this post


Link to post
Share on other sites
litlmike

Just curious if anyone's thought of testing the exit code of the ren command for errors, or does it even return one?

In some quick tests with renaming, when I get "Access is denied." for permissions issues, the exit code is 1, so perhaps a quick check of the exit code would help to return a more precise status of the result.

Something like...

Func FileRename($fr_FullPath, $fr_Rename)
    If $fr_Fullpath = "" Then
        Return -1
    ElseIf $fr_Rename = "" Then
        Return -1
    ElseIf Not FileExists($fr_Fullpath) Then
        Return -1
    Else
    ; Return the exitcode returned by the command
        Return _RunDOS("ren """& $fr_FullPath &""" """& $fr_Rename &"""")
    EndIf
Endfunc

I was looking at Run to see if it was feasible to capture the output of the command, but it doesn't look like it's possible to capture the exitcode of the command also when using Run. I'd like to suggest a change to the RunWait command to be able to attach StdOut and StdErr like the Run command so you could do a StdOutRead and StdErrRead to get the actual result of the command, while RunWait continues to return the actual exitcode of the command. In this example, you could then see what the errors were ("Access is denied.").

Good suggestion, repacked below:

"attachment=21499:_FileRename.zip" -Removed 07-29-2008 @ 8:57 AM PST

Edited by litlmike

Share this post


Link to post
Share on other sites
Gigglestick

I'd like to suggest a change to the RunWait command to be able to attach StdOut and StdErr like the Run command so you could do a StdOutRead and StdErrRead to get the actual result of the command, while RunWait continues to return the actual exitcode of the command. In this example, you could then see what the errors were ("Access is denied.").

Submitted this to Trac - Feature request #473

My UDFs: ExitCodes

Share this post


Link to post
Share on other sites
tehhahn

Hi,

why so complicated, three LOC are enough for this:

1. It makes no sense to check for a blank string ("") for $S_FILE, FileExists is enough!

2. To check if $S_RENAME is blank, is not enough! RegExp does the job.

3. One goal of UDFs should be to use no includes (One line does it all!).

ToDo: Retrieving all possible error codes for "rename" and handle them in the UDF.

;===============================================================================
; Function Name.....: _FileRename
; Description.......: Renames a file using the command "rename".
; Version...........: 1.0.4
; Change Date.......: 2008-07-29
; AutoIt Version....: 3.2.12.1
;
; Parameter(s)......: $S_FILE - String containing the directory or file to rename.
;                     $S_RENAME - String containing the new name of the file, without the path.
; Requirements(s)...: None
; Return Value(s)...: Success: Returns the exit code of the "rename" command.
;                     Failure: Returns 0 and sets @error to:
;                       1 = The file or folder $S_FILE does not exist.
;                       2 = $S_RENAME is an invalid filename.
;
; Author(s).........: xVivoCity
;                     Modified by: JellyFish666 & litlmike
;                     Modified by: teh_hahn <sPiTsHiT@gmx.de>
; Company...........: None
; URL...............: None
; Note(s)...........: None
;===============================================================================
Func _FileRename(Const $S_FILE, Const $S_RENAME)
    If Not FileExists($S_FILE) Then Return SetError(1, 0, 0)
    If Not StringRegExp($S_RENAME, '(?i)^[^<>\?":\|\\/\*]+$') Then Return SetError(2, 0, 0)

    Return RunWait(@ComSpec & ' /c ren "' & $S_FILE & '" "' & $S_RENAME & '"', "", @SW_HIDE)
EndFunc   ;==>_FileRename
Edited by tehhahn

Share this post


Link to post
Share on other sites
litlmike

Hi,

why so complicated, three LOC are enough for this:

1. It makes no sense to check for a blank string ("") for $S_FILE, FileExists is enough!

2. To check if $S_RENAME is blank, is not enough! RegExp does the job.

LOL! You are right! I totally missed that, all that matters is if the file exists or not. Glad you found that. Making adjustment now and re-packing.

Share this post


Link to post
Share on other sites
Valik

I can tell you right now, this will not be a standard UDF. It's stupid and I don't think you're right in your assessment. If you are right - check your hard drive, it could be failing.

Renaming/moving a file on the same volume can't be slow under normal circumstances. All it involves is changing a few things in the master file table (NTFS). That means a rename/move on the same volume is done in constant time regardless of the size of the file. A 1 byte or 10 GB file will rename/move at the same speed if done on the same volume. If you are moving a file cross-volume, then a copy & delete operation occurs which means the time increases compared to the size of the file.

Since a rename is nothing more than moving a file on the same volume, it's virtually instantaneous. The system goes in and updates the MFT with the new name and that's it. If it is not instant for you, something is serious wrong with your system. Maybe it needs defragmented. Or maybe the hard drive has a bad sector where the MFT is causing it to be slow. But something isn't right if same-volume moves are slow.

Share this post


Link to post
Share on other sites
litlmike

I can tell you right now, this will not be a standard UDF. It's stupid and I don't think you're right in your assessment. If you are right - check your hard drive, it could be failing.

Renaming/moving a file on the same volume can't be slow under normal circumstances. All it involves is changing a few things in the master file table (NTFS). That means a rename/move on the same volume is done in constant time regardless of the size of the file. A 1 byte or 10 GB file will rename/move at the same speed if done on the same volume. If you are moving a file cross-volume, then a copy & delete operation occurs which means the time increases compared to the size of the file.

Since a rename is nothing more than moving a file on the same volume, it's virtually instantaneous. The system goes in and updates the MFT with the new name and that's it. If it is not instant for you, something is serious wrong with your system. Maybe it needs defragmented. Or maybe the hard drive has a bad sector where the MFT is causing it to be slow. But something isn't right if same-volume moves are slow.

You know, that is a really good point, I didn't realize that FileMove could be used to Rename a file until you brought this up. Thanks.

Share this post


Link to post
Share on other sites
Innovative

This is my first release in the EXAMPLE SECTION and i've received so many flamings. I might need to consider hard before releasing next time.

Share this post


Link to post
Share on other sites
Valik

This is my first release in the EXAMPLE SECTION and i've received so many flamings. I might need to consider hard before releasing next time.

If you call what you've received in this thread flaming, then I suggest you lock your doors, unplug your internet connection and go live out the rest of your existence in the basement because what you've gotten here is some critical feedback but definitely not flaming. And it's well earned feedback at that since you took a long and complicated way to do something that's built into the language under the pretense the built-in functionality works in a way that simply is not the case.

Share this post


Link to post
Share on other sites
Gigglestick

@xVivoCity:

By the way, what OS are you using? I've noticed in Vista, general operations like deleting files (not via AutoIt), even a single file, requires a progress dialog, leading me to believe it's doing something extra with the information other than a simple file table change. Moves and copies in Explorer are similar, though renames do appear to still be instant.

If you're on Vista, I wonder if it's some underlying OS thing (indexing or something?) that's slowing down AutoIt's performance. I've never had an issue with FileMove for renames that I can recall... on 2000, XP, 2003, Vista, or 2008.


My UDFs: ExitCodes

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  

×