1. Computing & Technology

Discuss in my forum

Get Parent Folder / Directory

for a Specified File / Folder Name

By , About.com Guide

Delphi's RTL library exposes dozens of file name related functions and procedures.

You might be surprised that one function is "missing": how to get the parent folder (directory) for a specified file / folder name.

For example, for a given file named: "c:\My Documents\Pictures\ADP2008.gif", the parent folder is "c:\My Documents\Pictures".

If a folder is specified as "c:\My Documents\Pictures", the parent folder is then "c:\My Documents". Therefore, parent directory is the directory that is one level up from the specified directory.

Path.GetParentFolder

The easiest way to create the "GetParentFolder" function yourself, is to use some of the existing RTL routines.
 //returns the parent directory for the
 //provided "path" (file or directory)
 function GetParentDirectory(path : string) : string;
 begin
   result := ExpandFileName(path + '\..')
 end;
 
Note: A backslash followed by two dots is a carryover from DOS that indicates the parent folder. The ExpandFileName RTL function retrieves the full path and filename of a specified (relative) file.

Note 2: the GetParentDirectory function will work even if the "path" parameter provided does *not* present an existing file or folder.

Delphi tips navigator:
» Get Directory Creation, Modified, Last Accessed and Last Write Date and Time
« Get Windows Running Time

©2012 About.com. All rights reserved.

A part of The New York Times Company.