Monday, 10 September 2007

Returning the outer directory

Returning the directory before the current one should be a simple one-line call but I have so often seen a number of very highly convoluted ways of finding the last slash (\) in the directory string and using copy() and other ways that I have decided to relate a simple and direct way to obtain any or all directories prior to, and including the current one.

The problem with finding the last slash is that you have to watch out for cases where the current directory is a root directory. The good news is that you can ignore all of that.

You should know that finding the currently running exe program name including directories is Application.ExeName found in SysUtils. This should return something like..

C:\Program Files\CodeGear\Delphi\5.0\bin\MyProgram.exe

Of course the directory structure may be different as I'm sure you're not running your programs in the Delphi \bin directory :o)

But to get the directory that MyProgram.exe is running in, the call is ExtractFileDir(Application.ExeName). This returns..

C:\Program Files\CodeGear\Delphi\5.0\bin

ExtractFilePath() dies something similar. It simply returns the string up to the last delimiter (the slash). In other words, anything past the last delimiter is ignored as it is assumed to be the program name. Excellent, this means that we can use that fact on the above directory structure to return the previous directory.

PreviousDir := ExtractFilePath(ExtractFileDir(Application.ExeName));

This should return a directory structure of
C:\Program Files\CodeGear\Delphi\5.0\

We can continue to use ExtractFileDir() to return each directory in the tree until we reach the root directory (perhaps checking if PreviousDir = LastDir?). For example:

Dir := ExtractFilePath(ExtractFileDir(ExtractFileDir(Application.ExeName)));

Should return one directory up from the previous dir, or in this case:
C:\Program Files\CodeGear\Delphi\

So there you have it. A single call that returns the previous directory without having to bother with searching for the slash or worrying about the root directory issue.

4 comments:

  1. Andreas HausladenSeptember 10, 2007

    I wouldn't name the variable "Dir". As the ExtractFilePath function indicates, you get a Path and not a Dir (that is what ExtractFileDir returns).

    This differentiation saved me mayn times from concating wrong file names.

    ReplyDelete
  2. Excellent tip Andreas. Thanks.

    Steve

    ReplyDelete
  3. ExpandFileName(ExtractFileDir(Application.ExeName) + '\..')

    ReplyDelete
  4. AnonymousJuly 23, 2013

    thanks man, very good tip

    ReplyDelete

Note: only a member of this blog may post a comment.