1. Computing & Technology

Discuss in my forum

Programmatically Rename a Directory / Folder Using Delphi Code

Use RenameFile to Rename a Directory

By , About.com Guide

The RTL's RenameFile changes the name of a specified file.

How to Rename a Directory / Folder?

RenameFile returns false if the file cannot be renamed (for example, if the application does not have permission to modify the file) or if the new name specified represents the name of an existing file.

The implementation of the RenameFile function calls the MoveFile API function. MoveFile moves an existing file or a directory, including its children.

Moving IS Renaming

RenameFile is declared as :

 function RenameFile(const FileName, NewFileName: string): boolean;
 
To rename a directory (folder) you CAN use the RenameFile function.

If you have a folder named "new folder" under "c:\temp", to rename "new folder" to "my data" simply call the RenameFile as:

 RenameFile('c:\temp\new folder', 'c:\temp\my data'); 
If the function succeddes, the folder "new folder" will be renamed to "my data".

Note that the function will fail if there already is a directory named "my data" under "c:\temp".

That's it. Yes, RenameFile can rename folders also!

RenameFile CAN MOVE Folders!

RenameFile can therefore be used to actually move folders to a new location:
 RenameFile('c:\temp\new folder', 'c:\new root folder'); 
The above line will move the folder "new folder" (as a sub folder of "c:\temp") AND its children to "c:\new root folder".

Delphi tips navigator:
» Preserve Code Folding When Reopening a Delphi Project
« Specify Custom Icon for a Console Mode Delphi Application

©2012 About.com. All rights reserved.

A part of The New York Times Company.