Re: Delphi code to create a folder

Posted by DelphiLand Team on October 28, 2004:

In Reply to: Delphi code to create a folder posted by Alicia P12610 on October 28, 2004

: How do I create a folder in Delphi? If it does not exist yet, create it, else do nothing.

You check if the folder exists with DirectoryExists, and you create a new folder with CreateDir.

Example: let's assume a form with a button and an edit-box:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if DirectoryExists(Edit1.Text) then
    ShowMessage(Edit1.Text + ' exists')
  else begin
    if CreateDir(Edit1.Text) then
      ShowMessage('Folder created: ' + Edit1.Text)
    else
      ShowMessage('Could not create ' + Edit1.Text);
  end;
end;

CreateDir can only create directories that are one level "higher" then an existing directory. E.g., CreateDir('C:\Folder1\Folder2') only works if C:\Folder1 already exists, and likewise CreateDir('C:\F1\F2\F3') only works if C:\F1\F2 exists. For creating the "in-between" folders in one step, you use Delphi's ForceDirectories.

Note: this is a procedure, not a function, so it doesn't give you any feedback. For checking if the folder was really created, you can use DirectoryExists once again.

Here's an other example. Enter c:\a\b\c in the edit box, first try Button1, then try Button2.

procedure TForm1.Button2Click(Sender: TObject);
begin
  if DirectoryExists(Edit1.Text) then
    ShowMessage(Edit1.Text + ' exists already')
  else begin
    ForceDirectories(Edit1.Text);
    if DirectoryExists(Edit1.Text) then
      ShowMessage('Folder created: ' + Edit1.Text)
    else
      ShowMessage('Could not create ' + Edit1.Text);
  end;
end;

IMPORTANT NOTE:

DirectoryExists is located in Delphi's FILECTRL unit, so you have to add FILECTRL to the "uses" line in the unit where you use the function:

uses Windows, Messages, SysUtils { and so on...}, FILECTRL; 

Regards,
Jeff, DelphiLand Team