24 Votes

Lazarus: Rename or Move File

Tip by Delphian | 2014-08-23 at 20:10

I still remember the time when it was really difficult to carry out a simple file renaming in some programming languages. You had to work with Windows ShellApi and it was necessary to write several lines of code to only change the name of a file.

As you can see, it is much more easier in Lazarus today and it is also platform-independent:

RenameFile('C:\oldname.txt', 'C:\newname.txt');

The only thing, we have to do, is to call the function RenameFile with two parameters: As a first parameter, we are passing a string containing the old file name, as a second parameter the new name. Lazarus cares about the rest.

If the renaming hase been done successfully, the function returns true, false otherwise.

Move File to another Directory

In some operating systems such as Windows, it is even possible to use the function RenameFile to move files from one directory to another. For this, it is only necessary to vary the path of the file:

  dat_old, dat_new: string;  
  dat_old := 'C:\olddir\test.txt';
  dat_new := 'C:\newdir\test.txt';

  if RenameFile(dat_old, dat_new) then begin
    ShowMessage('Renaming was successful!');
  end else begin

With the code in this example, we move the file "test.txt" from the folder "C:\olddir\" to "C:\newdir\test.txt". Additionally, the example demonstrates the return value of true or false: Depending on the return value of RenameFile, a suitable message is shown.

Incidentally, RenameFile also works without specifying the complete file path when the files are stored in the current directory. Nonetheless, I would always recommend to specify the full path, because otherwise the function can come to unexpected results.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Delphi: Rename Folder

Tutorial | 0 Comments

Rename File to its Folder Name

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.