How do i dynamically create a folder if it does not exist yet while an application is
running? I need a snippet that says something like: if it does not exist, create else ...
Check with DirectoryExists, create with CreateDir.
Add a button
and an edit to your form and try the following example:
procedure TForm1.Button1Click(Sender: TObject);
begin
if DirectoryExists(Edit1.Text) then
ShowMessage(Edit1.Text + ' exists already')
else begin
if CreateDir(Edit1.Text) then
ShowMessage('Directory created: ' + Edit1.Text)
else
ShowMessage('Could not create ' + Edit1.Text);
end;
end;
CreateDir can only create directories that are one level away from an existing
directory.
E.g., CreateDir('C:\ABC\DEF') only works if C:\ABC already exists.
Likewise, CreateDir('C:\A\B\C')
only works if C:\A\B exists. For creating all the in-between levels in one step,
use ForceDirectories.
Note that this is a procedure, not a function, it does not return
a "success" value. If you want to check if the directory was really created, you
have to use DirectoryExists once again.
Here's an example, using a second button. 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('Directory created: ' + Edit1.Text)
else
ShowMessage('Could not create ' + Edit1.Text);
end;
end;
IMPORTANT:
DirectoryExists is declared in Delphi's FILECTRL unit, so don't forget to add FILECTRL
to the "uses"-declaration of the unit where you use this function:
uses Windows, Messages, SysUtils { and so on...}, FILECTRL;