Back


Lennie's Weekly Tip: Renaming an Existing File

22 July 2000 Ref. 30


If you need to rename a file from your Delphi application(s), then you can use the RenameFile function, which is a wrapper around the Windows API MoveFile function.

Declaration
-----------

function RenameFile(const OldName, NewName: string): Boolean;

Description
-----------
The RenameFile function attempts to change the name of the file specified by OldName to NewName.
If the operation succeeds, RenameFile returns TRUE.
If it cannot rename the file (for example, if a file called NewName already exists), it returns FALSE.

You cannot rename (move) a file across drives using RenameFile. You would need to first copy the file and then delete the old one.

See my tip on "Copying Files in Delphi" (Ref. 24) and on "Deleting Files in Delphi" (Ref. 25) for more information about deleting and copying files.

Example
-------

if not (RenameFile('A.TXT', 'B.TXT')) then
    Messagedlg('Error: Can''t rename file...', mterror, [mbok], 0);

In this example the RenameFile function will simply rename the file "A.TXT" to "B.TXT" and will display a error-message if unsuccessful.

NOTE: Remember to add the SysUtils unit to your application's uses-clause.

For more information read Delphi's on-line help.


Back