Back


Lennie's Weekly Tip : Force Directory Creation

07 July 2000 Ref. 28


When you try to create a subdirectory with the CreateDir-function and it's parent directories doesn't already exist, then CreateDir can't create the directory and will return FALSE. This is because Windows only allow directories to be created one at a time.

For Example
===========

If (CreateDir('C:\COOL\GAMES\TETRIS')) then
  Messagedlg('Directory successfully created...', mtinformation, [mbok], 0)
else
  Messagedlg('Error: Can''t create directory...', mterror, [mbok], 0);

In this example the CreateDir-function will return FALSE and a error message will be displayed, because the parent directories "COOL\GAMES\" don't exist.

To create a directory and all it's parent directories that don't't already exist, you can use the ForceDirectories function.
 

FORCEDIRECTORIES
================

Declaration
-----------

procedure ForceDirectories(Dir: string);

Description
------------
DOS and Windows only allow directories to be created one at a time.
For example, to create the C:\APPS\SALES\LOCAL directory, the APPS and SALES directories must exist before the LOCAL directory can be created.
Use ForceDirectories to create a directory and all parent directories that do not already exist.
 

Example
=======

uses
  FileCtrl;

const
  Dir = 'C:\COOL\GAMES\TETRIS';

begin
  ForceDirectories(Dir);

  if (DirectoryExists(Dir)) then
    Messagedlg('Directory successfully created...', mtinformation, [mbok], 0)
  else
    Messagedlg('Error: Can''t create directory...', mterror, [mbok], 0);

end;

In this example we use the ForceDirectories-function to create a subdirectory (\TETRIS), but because the parent directories (\COOL\GAMES\) don't already exist, they are created first.

Because ForceDirectories-function doesn't return a value of TRUE if the directory is created successfully or FALSE, otherwise. We use the DirectoryExists-function to check to see if the subdirectory (\TETRIS) was created successfully.
 

NOTE: Remember to add the FileCtrl unit to your application's uses-clause.


Back