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
AssignFile Assigns a file handle to a binary or text file
DeleteFile Delete a file specified by its file name
Erase Erase a file
IOResult Holds the return code of the last I/O operation
Rename Rename a file
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

 Buy Proxies at
 Buyproxies.io
 
 Download this web site as a Windows program.




 
Example code : Rename Unit1.dcu to Unit1.old and back again
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
 
unit Unit1;
 
interface
 
uses
  SysUtils,   // Unit containing the RenameFile command
  Forms, Dialogs;
 
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;
 
var
  
Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);

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;
 
end.
Hide full unit code
   Unit1.dcu renamed OK
   Unit1.dcu rename failed with error : 2
   Unit1.old renamed back OK
 
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Home Page