Creating this VCL application consists of the following steps:
- Create a project directory containing a file to rename.
- Create a VCL Form with button and label controls.
- Write the code to rename the file.
- Run the application.
To set up your project directory and a text file to copy
- Create a directory in which to store your project files.
- Either create or copy a text file to your project directory; then save it as MyFile.txt.
To create a VCL Form with a button and label
- Choose FileNewOtherDelphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer is displayed.
- From the Standard page of the Tool palette, place a TButton component on the form.
- From the Standard page of the Tool palette, place a TLabel component on the form.
To write the rename file procedure
- Select Button1 on the form.
- In the Object Inspector, double-click the OnClick action on the Events tab. The Code Editor displays, with the cursor in the TForm1.Button1Click (Delphi) or TForm1::Button1Click (C++) event handler block.
- At the cursor, type the following code:
if not RenameFile('MyFile.txt', 'YourFile.txt') then
Label1.Caption := 'Error renaming file!';
if( !RenameFile( "..\\MyFile.txt", "..\\YourFile.txt" )
Label1–>Caption = “Error renaming file”;
// the file parameters assume the target output directory is in your project directory
Note: You cannot rename (move) a file across drives using RenameFile. You would need to first copy the file and then delete the old one. In the runtime library, RenameFile is a wrapper around the Windows API MoveFile function, so MoveFile will not work across drives either.
To run the application
- Save your project file; then choose RunRun to build and run the application. The form displays.
- Click the button; If no message displays in the Label, check the file name in your project directory. MyFile.txt should is renamed as YourFile.txt.
- If the caption label displays the error message, recheck your event handler code.