Lazarus: Rename or Move File
Tip by Delphian | Last update on 2023-02-26 | Created on 2014-08-23
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:
var dat_old, dat_new: string; begin 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 ShowMessage('Error!'); end; end;
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
The author has not added a profile short description yet.
Show Profile
Related Topics
Windows Batch Script: Computer Shutdown
Tutorial | 2 Comments
Rename File to its Folder Name
Tutorial | 0 Comments
MySQL: Rename Name of a Database
Tip | 1 Comment
Lazarus: Detect Operating System (Compiler Switch)
Tutorial | 0 Comments
Delphi: Rename Folder
Tutorial | 0 Comments
Delphi/Lazarus: How to set up a Link to a Website in an Application
Tutorial | 0 Comments
VirtualBox: Change Date and Time
Tutorial | 10 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.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.