DelphiBasics
RenameFile
Function
Rename a file or directory SysUtils unit
 function RenameFile(const OldName, NewName string):Boolean;
Description
The RenameFile function renames OldName file or directory to NewName, returning True if successful.
 
If a file or directory name is given without a path, the file must be in the current directory.
Notes
You can rename a file onto a different drive, although this is not recommended.
Related commands
AssignFileAssigns a file handle to a binary or text file
DeleteFileDelete a file specified by its file name
EraseErase a file
IOResultHolds the return code of the last I/O operation
RenameRename a file
 Download this web site as a Windows program.




 
Example code : Rename Unit1.dcu to Unit1.old and back again
var
  oldName, newName : string;

begin
  // Try to rename the current Unit1.dcu to Uni1.old
  oldName := 'Unit1.dcu';
  newName := ChangeFileExt(oldName, '.old');
  if RenameFile(oldName, newName)
  then ShowMessage('Unit1.dcu renamed OK')
  else ShowMessage('Unit1.dcu rename failed with error : '+
                   IntToStr(GetLastError));

  // Let us try the same rename again
  if RenameFile(oldName, newName)
  then ShowMessage('Unit1.dcu renamed again OK')
  else ShowMessage('Unit1.dcu rename failed with error : '+
                   IntToStr(GetLastError));

  // Finally, let us rename the file back again
  if RenameFile(newName, oldName)
  then ShowMessage('Unit1.old renamed back OK')
  else ShowMessage('Unit1.old rename back failed with error : '+
                   IntToStr(GetLastError));
end;
Show full unit code
  Unit1.dcu renamed OK
  Unit1.dcu rename failed with error : 2
  Unit1.old renamed back OK
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page