DelphiBasics
Rename
Procedure
Rename a file System unit
 procedure Rename ( var FileHandle; NewFileName : string | PChar ) ;
Description
The Rename procedure renames a file given by FileHandle to a new name NewFileName.
 
The file must have been assigned the given FileHandle using the AssignFile routine.
Notes
Use RenameFile when you want to rename a file without needing to assign it.
Related commands
Erase Erase a file
RenameFile Rename a file or directory
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

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




 
Example code : Create a file, rename it, and then reopen it with the new name
// 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
  // The System unit does not need to be defined
  SysUtils,
  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
  myFile : TextFile;
  text   : string;

begin
  // Try to open the Test.txt file for writing to
  AssignFile(myFile, 'Test.txt');
  ReWrite(myFile);

  // Write a couple of well known words to this file
  WriteLn(myFile, 'Hello');
  WriteLn(myFile, 'World');

  // Close the file
  CloseFile(myFile);

  // Try to rename the file - ensure that no such file exists first!
  DeleteFile('NewName.txt');
  Rename(myFile, 'NewName.txt');

  // Now read the file
  AssignFile(myFile, 'NewName.txt');
  ReSet(myFile);

  // Display the file contents
  while not Eof(myFile) do
  begin
    ReadLn(myFile, text);
    ShowMessage(text);
  end;

  // Close the file for the last time
  CloseFile(myFile);
end;
 
end.
Hide full unit code
   Hello
   World
 
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Home Page