Renaming a File

From RAD Studio
Jump to: navigation, search

Go Up to Manipulating Files

To change a filename, use the System.SysUtils.RenameFile function:


 function RenameFile(const OldFileName, NewFileName: string): Boolean;


extern DELPHI_PACKAGE bool __fastcall RenameFile(const System::UnicodeString OldName,
    const System::UnicodeString NewName);

RenameFile changes a file name, identified by OldFileName, to the name specified by NewFileName. If the operation succeeds, RenameFile returns True. If it cannot rename the file (for example, if a file called NewFileName already exists), RenameFile returns False. For example:


 if not RenameFile('OLDNAME.TXT','NEWNAME.TXT') then
   ErrorMsg('Error renaming file!');


if (!RenameFile("OLDNAME.TXT","NEWNAME.TXT"))
    ErrorMsg("Error renaming file!");

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

Note: RenameFile in the RTL is a wrapper around the Windows API MoveFile function, so MoveFile will not work across drives either.

See Also