How to check whether a directory exists or not in delphi XE2?
Asked Answered
C

3

6

I want to create a directory say TestDir but only when that directory does not exist. I don't find the way the check the existence of that directory.

I am using following function to create the directory.

CreateDir('TestDir')

How should I make sure that I use this CreateDir function only when TestDir does not exist?

Con answered 19/2, 2013 at 6:34 Comment(2)
Don't bother checking before creating. It introduces a race condition. Just call ForceDirectories to check and create at the same time.Crossroads
Rob is quite right. Just create the directory and handle any failure appropriately.Boeotia
L
21

In Delphi XE2, you can use the IOUtils unit TDirectory record, like this:

uses IOUtils;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not TDirectory.Exists('test') then
    TDirectory.CreateDirectory('test');

In Delphi7, you can use the DirectoryExists function from the SysUtils unit:

uses SysUtils, Windows;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not DirectoryExists('test') then
    CreateDir('test');
Lashonlashond answered 19/2, 2013 at 6:43 Comment(0)
A
12

There's a routine in SysUtils called DirectoryExists that should do exactly what you need...

Aweinspiring answered 19/2, 2013 at 6:42 Comment(0)
M
3

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.

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;
Medium answered 30/7, 2016 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.