Renaming Files

From RAD Studio
Jump to: navigation, search

Go Up to How To Build VCL Forms Applications


Creating this VCL application consists of the following steps:

  1. Create a project directory containing a file to rename.
  2. Create a VCL Form with button and label controls.
  3. Write the code to rename the file.
  4. Run the application.

To set up your project directory and a text file to copy

  1. Create a directory in which to store your project files.
  2. 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

  1. Choose File > New > Other > Delphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer is displayed.
  2. From the Standard page of the Tool palette, place a TButton component on the form.
  3. From the Standard page of the Tool palette, place a TLabel component on the form.

To write the rename file procedure

  1. Select Button1 on the form.
  2. 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.
  3. 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

  1. Save your project file; then choose Run > Run to build and run the application. The form displays.
  2. 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.
  3. If the caption label displays the error message, recheck your event handler code.

See Also